SpringCloud
程序员文章站
2022-06-13 10:27:09
...
1、创建一个新的empty项目
2、创建api模块,使用Spring Initializr,无需添加依赖
创建User类,即公共的entity类
package com.xjj.api.entity;
public class User {
private Integer userId;
private String userName;
private String dbSource;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getDbSource() {
return dbSource;
}
public void setDbSource(String dbSource) {
this.dbSource = dbSource;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", dbSource='" + dbSource + '\'' +
'}';
}
}
api模块文件结构
3、创建provider模块,使用Spring Initializr
1、修改pom.xml文件,添加对公共类的依赖
<dependency>
<groupId>com.xjj</groupId>
<artifactId>api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
2、创建application.yaml文件
server:
port: 8081
spring:
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/cloud1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
application:
name: UserClient #在eureka中显示的名字
mybatis:
mapper-locations: classpath:mybatis/mapper/**/*.xml
config-location: classpath:myabtis/mybatis.cfg.xml
3、创建mybatis.cfg.xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
</configuration>
4、编写Dao、Service、Controller三层
package com.xjj.user8081provider.dao;
import com.xjj.api.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;
/**
* @author xjj
*/
@Component
@Mapper
public interface UserDao {
/**
* 根据传入的id来查询数据库中的信息
* @param userId
* @return
*/
User findById(@Param("userId")Integer userId);
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xjj.user8081provider.dao.UserDao">
<select id="findById" resultType="com.xjj.api.entity.User">
select * from user where user_id=#{userId}
</select>
</mapper>
package com.xjj.user8081provider.service;
import com.xjj.api.entity.User;
/**
* @author xjj
*/
public interface UserService {
/**
* 根据传入的id来查询数据库中的信息
* @param userId
* @return
*/
User findById(Integer userId);
}
package com.xjj.user8081provider.service;
import com.xjj.api.entity.User;
import com.xjj.user8081provider.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* @author xjj
*/
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserDao userDao;
@Override
public User findById(Integer userId) {
return userDao.findById(userId);
}
}
package com.xjj.user8081provider.controller;
import com.xjj.api.entity.User;
import com.xjj.user8081provider.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @author xjj
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("findById/{userId}")
@ResponseBody
public User findById(@PathVariable("userId")Integer userId){
User user=userService.findById(userId);
return user;
}
}
5、最终的文件结构
4、创建consumer端,使用Spring Initializr
1、修改pom.xml文件
<dependency>
<groupId>com.xjj</groupId>
<artifactId>api</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
2、修改application.yaml文件
server:
port: 80
3、创建Config配置文件
package com.xjj.user80consumer.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class Config {
/**
* 用来返回RestTemplate,可以根据这个实现对provider进行访问
* @return
*/
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
4、创建controller文件
package com.xjj.user80consumer.controller;
import com.xjj.api.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import java.util.List;
@Controller
@RequestMapping("/consumer/user")
public class UserController {
//这里因为还没有注册到eureka上,所以不能使用服务名字来定位,只能使用IP地址:端口号的形式
private static final String PROVIDER_PREFIX="http://localhost:8081";
//这里的前缀写的是provider端中application.yaml中配置的spring.application.name
//private static final String PROVIDER_PREFIX="http://UserClient";
@Autowired
private RestTemplate restTemplate;
/**
* 在User的provider端中使用了@RequestBody,所以必须是POST请求来传输User对象
* 根据GET请求获得User,然后通过RestTemplate来给8081端口的服务发送POST请求
* 其中的postForObject第一个参数为地址,第二个是post传输的参数,第三个为返回值类型
* @param user
* @return
*/
@RequestMapping("/addUser")
@ResponseBody
public boolean addUser(User user){
return restTemplate.postForObject(PROVIDER_PREFIX+"/user/addUser",user,Boolean.class);
}
/**
* 根据传来的Rest风格的请求,重新向User的provider端发起GET请求
* 第一个参数为地址,其中带着参数
* 第二个参数为返回值
* @param userId
* @return
*/
@RequestMapping("/findById/{userId}")
@ResponseBody
public User findById(@PathVariable("userId") Integer userId){
return restTemplate.getForObject(PROVIDER_PREFIX+"/user/findById/"+userId,User.class);
}
/**
* 方法同上,但是注意第二个参数应为List.class,因为返回值是List<User>类型
* @return
*/
@RequestMapping("/findAll")
@ResponseBody
public List<User> findAll(){
return restTemplate.getForObject(PROVIDER_PREFIX+"/user/findAll",List.class);
}
}
5、最终的文件结构
5、创建eureka服务
前言:在此之前先修改系统文件
1、修改application.yaml文件
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/ # eureka服务器端的地址
register-with-eureka: false
fetch-registry: false # 这两项是为了避免注册自己
2、修改主启动类
package com.xjj.eureka7001;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer //加上该注解
public class Eureka7001Application {
public static void main(String[] args) {
SpringApplication.run(Eureka7001Application.class, args);
}
}
3、向provider的pom.xml中添加依赖
4、修改provider端的主启动类
package com.xjj.user8081provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class User8081ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(User8081ProviderApplication.class, args);
}
}
6、创建eureka集群
1、重复第五步的依赖,并分别修改两个eureka的application.yaml
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/ # eureka服务器端的地址,写上所有的地址
register-with-eureka: false
fetch-registry: false # 这两项是为了避免注册自己
server:
port: 7001
eureka:
instance:
hostname: eureka7001.com
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/ # eureka服务器端的地址,写上所有的地址
register-with-eureka: false
fetch-registry: false # 这两项是为了避免注册自己
2、修改主启动类,添加@EnableEurekaServer
3、修改provider端的application.yaml文件
server:
port: 8081
spring:
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/cloud1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
application:
name: UserClient #在eureka中显示的名字
mybatis:
mapper-locations: classpath:mybatis/mapper/**/*.xml
config-location: classpath:mybatis/mybatis.cfg.xml
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/ # 写上所有的eureka服务器地址
7、使用ribbon
1、将consumer端的依赖改为这三者+api的依赖
2、修改consumer端的application.yaml文件
server:
port: 80
spring:
application:
name: UserConsumerClient # 设置注册名字
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/ #设置注册的eureka服务中心地址
3、修改config.class文件,添加@LoadBalanced注解
package com.xjj.user80consumer.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class Config {
/**
* 用来返回RestTemplate,可以根据这个实现对provider进行访问
* @return
*/
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
4、添加@EnableEurekaClient注解,将consumer注册到eureka服务中心上
package com.xjj.user80consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class User80ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(User80ConsumerApplication.class, args);
}
}
5、因为被注册到了eureka服务中心,所以可以将consumer端的controller中的部分代码进行修改
//这里因为还没有注册到eureka上,所以不能使用服务名字来定位,只能使用IP地址:端口号的形式
//private static final String PROVIDER_PREFIX="http://localhost:8081";
//这里的前缀写的是provider端中application.yaml中配置的spring.application.name
private static final String PROVIDER_PREFIX="http://UserClient";
6、重复第3大步,创建user8082-provider
1、修改pom.xml文件,添加对公共类的依赖
2、创建application.yaml文件
server:
port: 8082
spring:
application:
name: UserClient # 和8081注册成同一个名字,然后就可以均衡负载
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/cloud2?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
mybatis:
mapper-locations: classpath:mybatis/mapper/**/*.xml
config-location: classpath:mybatis/mybatis.cfg.xml
3、创建mybatis.cfg.xml文件
4、编写Dao、Service、Controller三层
7、使用自定义的ribbon策略
1、给主启动类添加注解@RibbonClient(name = “UserClient”,configuration = MyRule.class)
package com.xjj.user80consumer;
import com.xjj.ribbon.MyRule;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
@SpringBootApplication
@EnableEurekaClient
//针对于名字叫UserClient的微服务启动负载均衡,算法在MyRule类当中
@RibbonClient(name = "UserClient",configuration = MyRule.class)
public class User80ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(User80ConsumerApplication.class, args);
}
}
2、编写MyRule.class类
package com.xjj.ribbon;
import com.netflix.loadbalancer.IRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyRule {
@Bean
public IRule myrule(){
return new RibbonCustom();
}
}
3、编写真正的Ribbon自定义算法
package com.xjj.ribbon;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.List;
public class RibbonCustom extends AbstractLoadBalancerRule {
private int randomNum=0;
private int serverIndex=0;
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
}
Server server = null;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
List<Server> upList = lb.getReachableServers();
List<Server> allList = lb.getAllServers();
int serverCount = allList.size();
if (serverCount == 0) {
/*
* No servers. End regardless of pass, because subsequent passes
* only get more restrictive.
*/
return null;
}
if(randomNum<5) {
server = upList.get(serverIndex);
randomNum++;
}
else{
randomNum=0;
serverIndex++;
if(serverIndex>=serverCount) {
serverIndex = 0;
}
}
if (server == null) {
/*
* The only time this should happen is if the server list were
* somehow trimmed. This is a transient condition. Retry after
* yielding.
*/
Thread.yield();
continue;
}
if (server.isAlive()) {
return (server);
}
// Shouldn't actually happen.. but must be transient or a bug.
server = null;
Thread.yield();
}
return server;
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
}
}
8、使用feign
1、创建feign的application.yaml文件
server:
port: 80
spring:
application:
name: UserConsumerFeignClient
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
2、给api模块中加入新依赖OpenFeign
3、给api模块中添加新的service接口
package com.xjj.api.service;
import com.xjj.api.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
@FeignClient(value = "UserClient")
@Component
public interface UserFeignService {
@RequestMapping(value = "user/addUser",method = RequestMethod.GET)
@ResponseBody
boolean addUser(User user);
@RequestMapping(value = "user/findById/{userId}",method=RequestMethod.GET) //这里的地址一定要和provider中的controller的地址一样
@ResponseBody
User findById(@PathVariable("userId") Integer userId);
@RequestMapping(value = "user/findAll",method = RequestMethod.GET)
@ResponseBody
List<User> findAll();
}
4、给feign中创建controller
package com.xjj.userfeignconsumer.controller;
import com.xjj.api.entity.User;
import com.xjj.api.service.UserFeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@Controller
public class UserController {
@Autowired
private UserFeignService userFeignService;
@RequestMapping(value = "/consumer/user/addUser",method = RequestMethod.GET)
@ResponseBody
public Object addUser(User user){
return this.userFeignService.addUser(user);
}
@RequestMapping(value = "/consumer/user/findById/{userId}",method = RequestMethod.GET)
@ResponseBody
public User findById(@PathVariable("userId") Integer userId){
return this.userFeignService.findById(userId);
}
@RequestMapping(value = "/consumer/user/findAll",method = RequestMethod.GET)
@ResponseBody
public List<User> findAll(){
return this.userFeignService.findAll();
}
}
5、修改feign的主启动类
package com.xjj.userfeignconsumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.xjj.api.service"}) //去扫描api模块中的service接口
public class UserfeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(UserfeignConsumerApplication.class, args);
}
}
9、使用hystrix(熔断),基于provider端访问实现
1、hystrix的provider端,编写application.yaml
server:
port: 8081
spring:
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/cloud1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
application:
name: UserClient # 最好要和普通类的provider一样,否则容易混淆
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml
mapper-locations: classpath:mybatis/mapper/**/*.xml
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
2、hystrix的provider端编写三层加mybatis,将controller修改为以下
package com.xjj.user8081hystrixprovider.controller;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.xjj.api.entity.User;
import com.xjj.user8081hystrixprovider.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
/**
* @author 徐敬杰
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/findById/{userId}",method = RequestMethod.GET)
@ResponseBody
@HystrixCommand(fallbackMethod = "hystrixMethod")//当出现了异常,回去自动的使用这个方法
public User findById(@PathVariable("userId")Integer userId){
User user=userService.findById(userId);
if(user==null){
throw new RuntimeException("没有查询到,报错了");
}
return user;
}
public User hystrixMethod(@PathVariable("userId")Integer userId){
User user=new User();
user.setUserId(userId);
user.setUserName("该id不存在用户");
user.setDbSource("没有数据库");
return user;
}
}
3、hystrix的provider端在主启动类上加上注解
package com.xjj.user8081hystrixprovider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@EnableCircuitBreaker //打开hystrix
public class User8081HystrixProviderApplication {
public static void main(String[] args) {
SpringApplication.run(User8081HystrixProviderApplication.class, args);
}
}
10、使用Hystrix(降级),基于consumer端访问实现
1、在api模块中创建UserFeignServiceFallbackFactory类
package com.xjj.api.service;
import com.xjj.api.entity.User;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
//其中实现FallbackFactory的泛型为在Feign第8步中创建的service接口
public class UserFeignServiceFallbackFactory implements FallbackFactory<UserFeignService> {
@Override
public UserFeignService create(Throwable throwable){
return new UserFeignService() {
@Override
public User findById(Integer userId) {
User user=new User();
user.setUserId(userId);
user.setUserName("此刻服务已经停止工作");
user.setDbSource("没有数据库");
return user;
}
};
};
}
2、修改该service接口
package com.xjj.api.service;
import com.xjj.api.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
//新增了fallbackFactory属性
@FeignClient(value = "UserClient",fallbackFactory = UserFeignServiceFallbackFactory.class)
public interface UserFeignService {
@RequestMapping(value = "user/findById/{userId}",method=RequestMethod.GET)
@ResponseBody
User findById(@PathVariable("userId") Integer userId);
}
3、在hystrix的consumer端中的application.yaml文件中
feign:
hystrix:
enabled: true #打开新的配置
4、在hystrix的consumer端中的主启动类上新增包扫描
package com.xjj.userfeignconsumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.stereotype.Component;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.xjj.api.service"})
@ComponentScan(value = "com.xjj") // 注意扫描路径,最好把整个api的部分都囊括进去
public class UserfeignConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(UserfeignConsumerApplication.class, args);
}
}
11、完善provider微服务信息
1、给pom.xml文件添加新依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2、编写pom.xml中的build信息
<build>
<finalName>UserClient</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<configuration>
<delimiters>
<delimiter>$</delimiter>
</delimiters>
</configuration>
</plugin>
<!-- 这部分是原有的,保留下来 -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
3、编写application.yaml文件
server:
port: 8081
spring:
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/cloud1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
application:
name: UserClient #在eureka中显示的名字
mybatis:
mapper-locations: classpath:mybatis/mapper/**/*.xml
config-location: classpath:mybatis/mybatis.cfg.xml
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
instance:
instance-id: user8081-provider # 显示微服务别名
prefer-ip-address: true # 显示微服务ip地址
info:
app.name: app.name
company.name: company.name
build.artifactId: $project.artifactId$
build.version: $project.version$ # 用来显示info页面信息
4、完善微服务信息详解
12、HystrixDashboard图形化监控界面
1、创建新的模块,引入依赖
2、创建application.yaml文件
server:
port: 9001
3、修改主启动类
package com.xjj.hystrixdashboard;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;
@SpringBootApplication
@EnableHystrixDashboard //开启监控功能
public class HystrixdashboardApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixdashboardApplication.class, args);
}
}
4、给需要监控的provider都加上11步中完善微服务所需要的依赖,并给他们的application.yaml加上以下内容(为了防止http://192.168.84.1:8081/actuator/hystrix.stream出现404的情况)
management:
endpoints:
web:
exposure:
include: '*'
5、访问测试
13、添加zuul
1、引入web、eurekaclient、zuul的依赖
2、编写application.yaml文件
server:
port: 9527
spring:
application:
name: zuul
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
instance:
instance-id: gateway
prefer-ip-address: true
hostname: myzuul.com
zuul: # 因为暴露了微服务名字,所以配置一下
prefix: /client # 统一的域名前缀
ignored-services: "*" # 无法使用这个微服务名字来调用该服务
routes:
mydept.serviceId: userclient # 将这个地址等同于下面这个地址
mydept.path: /microsoft/**
3、改写主启动类
package com.xjj.zuul;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
4、修改myzuul.com 为127.0.0.1在host文件中
5、测试访问地址http://myzuul.com:9527/microsoft/user/findById/1
格式为myzuul.com:9527/微服务名字/请求路径,而在application.yaml中微服务名称变成了microsoft
14、config服务端
1、复制ssh地址或者http地址
2、创建一个自己的本地库
git clone http地址或者ssh地址
3、创建application.yaml
touch application.yaml
4、修改application.yaml内容,并且保存为utf-8编码格式
spring:
profiles:
active:
- dev
---
spring:
profiles: dev # 开发环境
application:
name: microservice-dev
---
spring:
profiles: test # 测试环境
application:
name: microservice-test
5、提交到远程库中
git add .
git commit -m "init file"
git push origin master # 需要先设置user和email
6、创建新模块
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>5.1.3.201810200350-r</version>
</dependency>
7、创建application.yaml
server:
port: 3344
spring:
application:
name: github-3344
cloud:
config:
server:
git:
uri: https://github.com/wdnmdsb/spring-cloud.git
8、主启动类
package com.xjj.github3344;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class Github3344Application {
public static void main(String[] args) {
SpringApplication.run(Github3344Application.class, args);
}
}
9、修改host内容127.0.0.1 config-3344.com
10、根据测试地址http://config-3344.com:3344/application-dev.yaml测试
15、config客户端
1、保存application-client.yaml文件,并上传到github上
spring:
profiles:
active:
- dev
---
server:
port: 8201
spring:
profiles: dev
application:
name: microservicecloud-config-client
eureka:
client:
service-url:
defaultZone: http://eureka-dev.com:7001/eureka/
---
server:
port: 8202
spring:
profiles: test
application:
name: microservicecloud-config-client
eureka:
client:
service-url:
defaultZone: http://eureka-test.com:7001/eureka/
2、创建新工程
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.jgit</groupId>
<artifactId>org.eclipse.jgit</artifactId>
<version>5.1.3.201810200350-r</version>
</dependency>
3、编写bootstrap.yaml,用来读取github端的配置文件
spring:
cloud:
config:
name: application-client # 读取名字叫application-client.yaml的文件,不允许带上后缀名
profile: dev # profile为dev
label: master
uri: http://config-3344.com:3344 # 连接到config的server端,server端会自动帮我们读取文件,我们从server端读取
4、编写application.yaml
spring:
application:
name: github-3355-client # 其实写不写都可以,没有什么要求
5、编写一个controller
package com.xjj.github3355client.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class ClientController {
//因为会自动的读取到github端的application-client文件,所以可以读取到没有写入到本地的内容,因为都是从github端读来的,这个controller只是作为验证使用
@Value("${spring.application.name}")
private String applicationName;
@Value("${eureka.client.service-url.defaultZone}")
private String eurekaServers;
@Value("${server.port}")
private String serverPort;
@RequestMapping("/config")
@ResponseBody
public String config(){
return "applicationName:"+applicationName
+"eurekaServers:"+eurekaServers
+"serverPort"+serverPort;
}
}
6、再次给host文件添加新内容127.0.0.1 client-config.com
7、测试
先使用http://config-3344.com:3344/application-client-dev.yaml观察是否连接成功
再使用http://client-config.com:8201/config判断application-client是否被server端读取并且被client端读取,使用8201是因为bootstrap.yaml中读取的yaml文件是dev,属于8201端口
16、实战
1、在本地库分别创建microservicecloud-config-eureka-client.yaml配置文件和microservicecloud-config-user-client.yaml
spring:
profiles:
active:
- dev
---
server:
port: 7001 # 注册中心占用7001端口
spring:
profiles: dev
application:
name: microservicecloud-config-eureka-client
eureka:
instance:
hostname: eureka7001.com
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/
---
server:
port: 7001
spring:
profiles: test
application:
name: microservicecloud-config-eureka-client
eureka:
instance:
hostname: eureka7001.com
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka/
fetch-registry: false
register-with-eureka: false
spring:
profiles:
active:
- dev
---
server:
port: 8001
spring:
profiles: dev
application:
name: microservicecloud-config-user-client
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/cloud1?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml
mapper-locations: classpath:mybatis/mapper/**/*.xml
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka
instance:
instance-id: user-8081.com
prefer-ip-address: true
---
server:
port: 8001
spring:
profiles: test
application:
name: microservicecloud-config-user-client
datasource:
username: root
password: 1234
url: jdbc:mysql://localhost:3306/cloud2?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC
driver-class-name: com.mysql.jdbc.Driver
mybatis:
config-location: classpath:mybatis/mybatis.cfg.xml
mapper-locations: classpath:mybatis/mapper/**/*.xml
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka
instance:
instance-id: user-8081.com
prefer-ip-address: true
2、创建新的eureka-server端microservicecloud-config-eureka-client-7001
3、创建bootstrap.yaml
spring:
cloud:
config:
name: microservicecloud-config-eureka-client # 从github上读取的资源文件的的名字
profile: dev
label: master
uri: http://config-3344.com:3344 # 连接github的连接
4、创建application.yaml
spring:
application:
name: microservicecloud-config-eureka-client
5、给主启动类加上注解@EnableEurekaServer
6、创建新的eureka-client端microservicecloud-config-user-client-8001
7、创建bootstrap.yaml文件
spring:
cloud:
config:
name: microservicecloud-config-dept-client
profile: test
label: master
uri: http://config-3344.com:3344
8、创建application.yaml文件
spring:
application:
name: microservicecloud-config-user-client-8081
9、修改主启动类
package com.xjj.microservicecloudconfiguserclient8001;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class MicroservicecloudConfigUserClient8001Application {
public static void main(String[] args) {
SpringApplication.run(MicroservicecloudConfigUserClient8001Application.class, args);
}
}
10、编写三层+mybatis配置文件
11、使用eureka7001.com:7001和http://localhost:8001/user/findById/1来进行测试
推荐阅读
-
Nacos(四):SpringCloud项目中接入Nacos作为配置中心
-
springboot2.0和springcloud Finchley版项目搭建(包含eureka,gateWay,Freign,Hystrix)
-
SpringCloud之消息总线Spring Cloud Bus实例代码
-
SpringCloud之分布式配置中心Spring Cloud Config高可用配置实例代码
-
SpringCloud之服务注册与发现Spring Cloud Eureka实例代码
-
SpringCloud重试机制配置详解
-
SpringCloud-创建服务消费者-Feign方式(附代码下载)
-
实战SpringCloud响应式微服务系列教程(第六章)
-
springcloud学习之路: (四) springcloud集成Hystrix服务保护
-
springcloud实现注册中心Eureka