SpringCloud入门
入门组件
eureka:服务注册与发现
Ribbon:负载均衡
Hystrix:断路器
Zuul:路由网关
SpringCloud Config:分布式配置中心
入门实践
创建父项目
1.新建maven项目microservice
注意构件坐标:设置自己的包名。
编辑pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.hand.cloud</groupId>
<artifactId>microservice</artifactId>
<version>1.0-SNAPSHOT</version>
<modules>
<module>microservice-api</module>
<module>microservice-provider-dept-8001</module>
<module>microservice-provider-dept-8002</module>
<module>microservice-provider-dept-8003</module>
<module>microservice-eureka-7001</module>
<module>microservice-eureka-7002</module>
<module>microservice-eureka-7003</module>
<module>microservice-consumer-dept-80</module>
<module>microservice-consumer-dept-feign-8082</module>
<module>springcloud-provider-hystrix</module>
<module>microservice-consumer-hystrix-dashboard</module>
<module>microservice-zuul-9527</module>
</modules>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<junit.version>4.12</junit.version>
<log4j.version>1.2.17</log4j.version>
<lombok.version>1.18.16</lombok.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Dalston.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.5.9.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.31</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
</project>
2.创建公共子模块microservice-api
引入Lombok依赖
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
编写实体类
@NoArgsConstructor
@Data
@Accessors(chain=true)
/**
* 必须序列化
*/
public class Dept implements Serializable
{
/**
* 主键
*/
private Long deptno;
/**
* 部门名称
*/
private String dname;
/**
* 数据库
*/
private String db_source;
public Dept(String dname)
{
super();
this.dname = dname;
}
}
3.创建服务提供者microservice-provider-dept-8001模块
编辑pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>microservice</artifactId>
<groupId>com.hand.cloud</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>microservice-consumer-dept-80</artifactId>
<dependencies>
<!-- 引入公共模块api-->
<dependency>
<groupId>com.hand.cloud</groupId>
<artifactId>microservice-api</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 修改后立即生效,热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon-eureka</artifactId>
<version>2.2.5</version>
</dependency>
</dependencies>
</project>
新建application.yml
server:
port: 8001
mybatis:
#config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径
type-aliases-package: com.hand.springcloud.entities # 所有Entity别名类所在包
mapper-locations:
- classpath:mybatis/mapper/**/*.xml # mapper映射文件
spring:
application:
name: microservice-dept
datasource:
type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型
driver-class-name: com.mysql.cj.jdbc.Driver
#driver-class-name: org.gjt.mm.mysql.Driver # mysql驱动包
url: jdbc:mysql://localhost:3306/cloudDB01 # 数据库名称
username: root
password: root
dbcp2:
min-idle: 5 # 数据库连接池的最小维持连接数
initial-size: 5 # 初始化连接数
max-total: 5 # 最大连接数
max-wait-millis: 200 # 等待连接获取的最大超时时间
执行MySQL脚本
DROP DATABASE IF EXISTS cloudDB01;
CREATE DATABASE cloudDB01 CHARACTER SET UTF8;
USE cloudDB01;
CREATE TABLE dept
(
deptno BIGINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
dname VARCHAR(60),
db_source VARCHAR(60)
);
INSERT INTO dept(dname,db_source) VALUES('开发部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('人事部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('财务部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('市场部',DATABASE());
INSERT INTO dept(dname,db_source) VALUES('运维部',DATABASE());
SELECT * FROM dept;
创建Dao层接口
@Mapper
public interface DeptDao{
public boolean addDept(Dept dept);
public Dept findById(Long id);
public List<Dept> findAll();
}
在src/main/resources/mybatis路径下创建mapper文件DeptMapper.xml
<?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.hand.cloud.dao.DeptDao">
<resultMap id="depno" type="integer"></resultMap>
<select id="findAll" resultType="com.hand.cloud.entities.Dept">
select deptno,dname,db_source from dept;
</select>
<select id="findById" resultType="com.hand.cloud.entities.Dept" parameterType="long">
select deptno,dname,db_source from dept where deptno=#{deptno};
</select>
<insert id="addDept" parameterType="com.hand.cloud.entities.Dept">
insert into dept (dname,db_source) value (#{dname},#{db_source})
</insert>
</mapper>
创建service和serviceImpl
/** * @author Administrator */public interface DeptService { /** * 添加 * @param dept * @return */ public boolean add(Dept dept); /** * 按id查询 * @param id * @return */ public Dept get(Long id); /** * 查询全部 * @return */ public List<Dept> list();}
/** * @author Administrator */@Servicepublic class DeptServiceImpl implements DeptService { @Autowired DeptDao deptDao; @Override public boolean add(Dept dept) { return deptDao.addDept(dept); } @Override public Dept get(Long id) { return deptDao.findById(id); } @Override public List<Dept> list() { return deptDao.findAll(); }}
创建controller
/** * @author Administrator */@RestControllerpublic class DeptController{ @Autowired private DeptService service; @RequestMapping(value="/dept/add",method= RequestMethod.POST) public boolean add(@RequestBody Dept dept) { return service.add(dept); } @RequestMapping(value="/dept/get/{id}",method=RequestMethod.GET) public Dept get(@PathVariable("id") Long id) { return service.get(id); } @RequestMapping(value="/dept/list",method=RequestMethod.GET) public List<Dept> list() { return service.list(); } /** * DiscoveryClient 可以用来获取一些配置的信息,得到具体的微服务! */ @Autowired private DiscoveryClient client; /** * 获取一些注册进来的微服务的信息~, * * @return */ @GetMapping("/dept/discovery") public Object discovery() { // 获取微服务列表的清单 List<String> services = client.getServices(); System.out.println("discovery=>services:" + services); // 得到一个具体的微服务信息,通过具体的微服务id,applicaioinName; List<ServiceInstance> instances = client.getInstances("microservice-dept"); for (ServiceInstance instance : instances) { System.out.println( instance.getHost() + "\t" + // 主机名称 instance.getPort() + "\t" + // 端口号 instance.getUri() + "\t" + // uri instance.getServiceId() // 服务id ); } return this.client; }}
创建启动类 DeptProviderApp-8001
@SpringBootApplication@EnableHystrixDashboardpublic class DeptProviderApp-8001 { public static void main(String[] args){ SpringApplication.run(DeptProvider8001App.class,args); }}
测试访问http://localhost:8001/dept/discovery
http://localhost:8001/dept/list
创建消费者microservice-consumer-8081
修改依赖
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>microservice</artifactId> <groupId>com.hand.cloud</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microservice-consumer-8081</artifactId> <dependencies> <dependency> <groupId>com.hand.cloud</groupId> <artifactId>microservice-api</artifactId> <version>${project.version}</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 修改后立即生效,热部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>com.netflix.ribbon</groupId> <artifactId>ribbon-eureka</artifactId> <version>2.2.5</version> </dependency> </dependencies></project>
新建application.yml
server: port: 8081spring: application: name: consumereureka: client: register-with-eureka: false #false表示不向注册中心注册自己。 service-url: defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka
创建类ConfigBean
@Configurationpublic class ConfigBean { @Bean public RestTemplate getRestTemplate() { return new RestTemplate(); }}
创建controller类
@RestControllerpublic class DeptConsumerController { private static final String REST_URL_PREFIX = "http://localhost:8001"; @Autowired private RestTemplate restTemplate; @RequestMapping(value="consumer/dept/add") public boolean add(Dept dept) { return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class); } @RequestMapping(value="consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { return restTemplate.getForObject(REST_URL_PREFIX+"/dept/get/"+id,Dept.class); } @RequestMapping(value="consumer/dept/list") public List<Dept> list() { return restTemplate.getForObject(REST_URL_PREFIX+"/dept/list", List.class); }}
编写主启动类
@SpringBootApplicationpublic class DeptConsumerApp-8081 { public static void main(String[] args) { SpringApplication.run(DeptConsumerApp.class,args); }}
测试http://localhost:8081/consumer/dep/list
构建Eureka服务注册中心
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>microservice</artifactId> <groupId>com.hand.cloud</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>microservice-eureka-7001</artifactId> <dependencies> <!--eureka-server服务端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> <!-- 修改后立即生效,热部署 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> </dependencies></project>
创建application.yml
server: port: 7001eureka: instance: hostname: eureka7001.com #eureka服务端的实例名称 client: register-with-eureka: false #false表示不向注册中心注册自己。 fetch-registry: false #false表示自己就是注册中心,不需要去检索服务 service-url: #设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址。 #单机 defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #集群 defaultZone: http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka
创建启动类
@EnableEurekaServer@SpringBootApplicationpublic class EurekaServerApp-7001 { public static void main(String[] args) { SpringApplication.run(EurekaServer7001App.class,args); }}
改造8001模块
添加eureka依赖
<!-- 老版本eureka --><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency>
修改yml配置文件
server: port: 8001eureka: instance: instance-id: provider8001 prefer-ip-address: true client: #客户端注册进eureka服务列表内 service-url: defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eureka, http://eureka7003.com:7003/eurekamybatis: #config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径 type-aliases-package: com.hand.springcloud.entities # 所有Entity别名类所在包 mapper-locations: - classpath:mybatis/mapper/**/*.xml # mapper映射文件spring: application: name: microservice-dept datasource: type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型 driver-class-name: com.mysql.cj.jdbc.Driver #driver-class-name: org.gjt.mm.mysql.Driver # mysql驱动包 url: jdbc:mysql://localhost:3306/cloudDB01 # 数据库名称 username: root password: root dbcp2: min-idle: 5 # 数据库连接池的最小维持连接数 initial-size: 5 # 初始化连接数 max-total: 5 # 最大连接数 max-wait-millis: 200 # 等待连接获取的最大超时时间
在8001启动类中添加注解@EnableEurekaClient或@EnableDiscoveryClient
@EnableDiscoveryClient@SpringBootApplication@EnableHystrixDashboardpublic class DeptProvider8001App { public static void main(String[] args){ SpringApplication.run(DeptProvider8001App.class,args); }}
启动测试http://localhost:7001
Eureka集群配置
复制7001模块,修改端口7002,7003
修改8081模块添加Ribbon依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId></dependency>
修改80模块的ConfigBean,添加@LoadBalanced
@Configurationpublic class ConfigBean { @Bean @LoadBalanced public RestTemplate getRestTemplate() { return new RestTemplate(); }}
修改8081模块的controller,访问地址为8001的(spring.application.name:microservice-dept)
//private static final String REST_URL_PREFIX = "http://localhost:8001";private static final String REST_URL_PREFIX = "http://MICROSERVICE-DEPT";
启动类添加@EnableEurekaClient
测试http://localhost:8080/consumer/dept/list
Ribbon负载均衡
复制8001模块,命名8002,8003
复制数据库cloudDB01,命名cloudDB02,cloudDB03
在8081模块,自定义规则并调用
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cmRJUUrM-1629960162903)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210721204334158.png)]
public class RandomRule extends AbstractLoadBalancerRule{ // total = 0 // 当total==5以后,我们指针才能往下走, // index = 0 // 当前对外提供服务的服务器地址, // total需要重新置为零,但是已经达到过一个5次,我们的index = 1 // 分析:我们5次,但是微服务只有8001 8002 8003 三台 // private int total = 0; // 总共被调用的次数,目前要求每台被调用5次 private int currentIndex = 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; }// int index = rand.nextInt(serverCount);// java.util.Random().nextInt(3);// server = upList.get(index);// private int total = 0; // 总共被调用的次数,目前要求每台被调用5次// private int currentIndex = 0; // 当前提供服务的机器号 if(total < 5) { server = upList.get(currentIndex); total++; }else { total = 0; currentIndex++; if(currentIndex >= upList.size()) { currentIndex = 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 clientConfig) { // TODO Auto-generated method stub }}
@Configurationpublic class MySelfRule{ @Bean public IRule myRule() { /** * *1、RoundRobinRule:轮询 *2、RandomRule:随机 *3、AvailabilityFilteringRule:先过滤掉多次访问故障处于熔断器跳闸状态、并发连接 *4、WeightedResponseTimeRule:根据平均相应时间计算所有服务的权重,相应时间越快服务权重越大,被选中的概率越高。若刚启动时统计信息不足,则使用 *5、RetryRule:按照RoundRobinRule的策略获取服务,若失败则在指定时间内重试,获取可用的服务 *6、BestAvailableRule:先过滤掉由于多次访问故障而处于熔断器跳闸状态的服务,然后选择一个并发量最小的服务 *7、ZoneAvoidanceRule:默认规则,复合判断服务所在区域的性能和服务的可用性选择服务器 * */ return new RandomRule(); }
Feign:
复制8081 重构为8082
添加feign依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId></dependency>
修改接口
@FeignClient(value = "MICROSERVICE-DEPT")public interface DeptClientService{ @RequestMapping(value = "/dept/get/{id}",method = RequestMethod.GET) public Dept get(@PathVariable("id") long id); @RequestMapping(value = "/dept/list",method = RequestMethod.GET) public List<Dept> list(); @RequestMapping(value = "/dept/add",method = RequestMethod.POST) public boolean add(Dept dept);}
主启动类添加注解@EnableFeignClients(basePackages= {“com.hand.cloud”})
@SpringBootApplication@EnableEurekaClient@EnableFeignClients(basePackages= {"com.hand.springcloud"})public class DeptConsumer80_Feign_App{ public static void main(String[] args) { SpringApplication.run(DeptConsumer80_Feign_App.class, args); }}
修改controller
@RestController@RequestMapping("consumer")public class DeptConsumerController { @Autowired DeptClientService deptClientService; @GetMapping("list") public List<Dept> findAll(){ return deptClientService.queryAll(); } @RequestMapping("get/{id}") public Dept findOne(@PathVariable("id") Long id){ return deptClientService.queryById(id); } @PostMapping("add") public Boolean add(Dept dept){ return deptClientService.addDept(dept); }}
访问http://localhost:8082/consumer/list
Feign集成了Ribbon,Feign只需要定义服务绑定接口且以声明式的方法,优雅而简单的实现了服务的调用。
Hystrix
熔断
复制8001创建8002
添加hystrix依赖
<!-- hystrix --><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId></dependency>
修改yml文件
eureka: instance: instance-id: microservice-dept8002-hystrix #自定义服务名称信息
修改controller文件
@RestControllerpublic class DeptController{ @Autowired private DeptService service = null; @RequestMapping(value="/dept/get/{id}",method=RequestMethod.GET) @HystrixCommand(fallbackMethod = "processHystrix_Get") public Dept get(@PathVariable("id") Long id) { Dept dept = this.service.get(id); if(null == dept) { throw new RuntimeException("该ID:"+id+"没有没有对应的信息"); } return dept; } public Dept processHystrix_Get(@PathVariable("id") Long id) { return new Dept().setDeptno(id).setDname("该ID:"+id+"没有没有对应的信息,null--@HystrixCommand").setDb_source("no this database in MySQL"); }}
修改主启动类
@EnableDiscoveryClient@SpringBootApplication@EnableHystrixDashboardpublic class DeptProvider8002App { public static void main(String[] args){ SpringApplication.run(DeptProvider8001App.class,args); }}
访问http://localhost:8082/consumer/get/3
降级
复制8001创建8002
修改service接口
@Component@FeignClient(value = "MICROSERVICE-DEPT",fallbackFactory = DeptClientServiceFallBackFactory.class)public interface DeptService { @GetMapping("/dept/get/{id}") Dept queryById(@PathVariable("id") Long id); @RequestMapping("/dept/list") List<Dept> queryAll(); @PostMapping("/dept/add") Boolean addDept(Dept dept);}
添加一个降级类
@Componentpublic class DeptClientServiceFallBackFactory implements FallbackFactory<DeptClientService> { @Override public DeptClientService create(Throwable throwable) { return new DeptClientService() { @Override public Dept queryById(Long id) { Dept dept =new Dept(); dept.setDeptno(id); dept.setDname("空"+id+"null"); dept.setDb_source("没有找到--降级"); return dept; } @Override public List<Dept> queryAll() { return null; } @Override public Boolean addDept(Dept dept) { return false; } }; }}
访问http://localhost:8082/consumer/get/1
zuul
新建模块microservice-zuul
<!-- zuul路由网关 --><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId></dependency><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId></dependency><!-- actuator监控 --><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId></dependency><!-- hystrix容错--><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId></dependency><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId></dependency><!-- 日常标配 --><dependency> <groupId>com.hand.cloud</groupId> <artifactId>microservice-api</artifactId> <version>1.0-SNAPSHOT</version></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jetty</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId></dependency><!-- 热部署插件 --><dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId></dependency>
编辑yml
server: port: 8770spring: application: name: springcloud-zuul #微服务名称# eureka 注册中心配置eureka: client: service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ instance: #实例的id instance-id: zuul9527.com prefer-ip-address: true # 显示ipinfo: app.name: com.hand # 项目名称 company.name: hand # 公司名称# zull 路由网关配置zuul: # 路由相关配置 # 原来访问路由 eg:http://www.cspStudy.com:9527/springcloud-provider-dept/dept/get/1 # zull路由配置后访问路由 eg:http://www.cspstudy.com:9527/haust/mydept/dept/get/1 routes: mydept.serviceId: microservice-dept # eureka注册中心的服务提供方路由名称 mydept.path: /** #将eureka注册中心的服务提供方路由名称 改为自定义路由名称 # 不能再使用这个路径访问了,*: 忽略,隐藏全部的服务名称~ ignored-services: "*" # 设置公共的前缀 prefix: /zuul
编辑主启动类
@SpringBootApplication@EnableZuulProxypublic class Zuul8770 { public static void main(String[] args) { SpringApplication.run(Zuul8770.class,args); }}
启动访问http://localhost:8770/dept/get/1
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VfrlQjXV-1629960162905)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20210728203007250.png)]
SpringCloud Config
创建CloudConfig模块
从本地上传配置文件到git仓库
spring: profiles: active: - dev---spring: profiles: dev # 开发环境 application: name: microservice-config-noodles-dev---spring: profiles: test # 测试环境 application: name: microservice-config-noodles-test
编辑pom,添加依赖
dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
编辑yml
server: port: 3344 enable-self-preservation: falsespring: application: name: cloudconfig cloud: config: server: git: uri: https://gitee.com/superyun666/cloudconfig.git #github上仓库的ssh地址eureka: client: service-url: defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/,http://localhost:7003/eureka/
编辑启动类
@SpringBootApplication@EnableConfigServer@EnableEurekaClientpublic class CloudconfigApplication { public static void main(String[] args) { SpringApplication.run(CloudconfigApplication.class, args); }
启动测试http://localhost:3344/application-dev.yml
config测试
添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId></dependency><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId></dependency><dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-client</artifactId></dependency>
编辑bootstrap.yml
spring: cloud: config: uri: http://localhost:3344 profile: dev label: master name: configclienteureka: client: serviceUrl: defaultZone: http://localhost:7001/eureka/
编辑application.yml
server: port: 3355# enable-self-preservation: falsespring: application: name: configclient cloud: config: enabled: falseeureka: client: service-url: defaultZone: http://localhost:7001/eureka/
编辑启动类
@SpringBootApplication@EnableDiscoveryClientpublic class CloudCientApplication { public static void main(String[] args) { SpringApplication.run(CloudCientApplication.class,args); }}
编辑controller测试
@RestControllerpublic class ConfigClientController { @Value("${spring.application.name}") private String applicationName; @Value("${eureka.client.service-url.defaultZone}") private String eurekaServers; @Value("${server.port}") private String port; @RequestMapping("/config") public String getConfig() { String str = "applicationName: " + applicationName + "\t eurekaServers:" + eurekaServers + "\t port: " + port; System.out.println("******str: " + str); return "applicationName: " + applicationName + "\t eurekaServers:" + eurekaServers + "\t port: " + port; } @RequestMapping("/hello") public String hello(){ return "hello"; }}
测试http://localhost:8201/config