9、完整步骤
9.0、SQL
CREATE DATABASE /*!32312 IF NOT EXISTS*/`clouddb01` /*!40100 DEFAULT CHARACTER SET utf8mb4 */; USE `clouddb01`; /*Table structure for table `dept` */ DROP TABLE IF EXISTS `dept`; CREATE TABLE `dept` ( `deptno` int(11) NOT NULL, `dname` varchar(50) DEFAULT NULL, `db_source` varchar(50) DEFAULT NULL, PRIMARY KEY (`deptno`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; /*Data for the table `dept` */ insert into `dept`(`deptno`,`dname`,`db_source`) values (10,'人力部','db01'),(20,'技术部','db01'),(30,'财务','db01');
9.1、父工程POM
<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.yjiu.cloud</groupId> <artifactId>microservicecloud-parent</artifactId> <version>0.0.1-SNAPSHOT</version> <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.16.18</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>5.0.4</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> <build> <finalName>microservicecloud</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> <delimit>$</delimit> </delimiters> </configuration> </plugin> </plugins> </build> </project>
9.2、microservicecloud-api工程
9.2.1、工程图
9.2.2、POM文件
<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> <parent> <groupId>com.yjiu.cloud</groupId> <artifactId>microservicecloud-parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>microservicecloud-api</artifactId><!-- 当前Module我自己叫什么名字 --> <dependencies><!-- 当前Module需要用到的jar包,按自己需求添加,如果父类已经包含了,可以不用写版本号 --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency> </dependencies> </project>
9.2.3、POJO
package com.yjiu.cloud.pojo; import java.io.Serializable; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @NoArgsConstructor @AllArgsConstructor @Data @Accessors(chain=true) public class Dept implements Serializable// entity --orm--- db_table { private Long deptno; // 主键 private String dname; // 部门名称 private String db_source;// 来自那个数据库,因为微服务架构可以一个服务对应一个数据库,同一个信息被存储到不同数据库 public Dept(String dname) { super(); this.dname = dname; } }
9.2.3、Service接口层【@FeignClient()】
package com.yjiu.cloud.service; import java.util.List; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import com.yjiu.cloud.pojo.Dept; /** 面向接口 新建一个实现了FallbackFactory接口的类DeptClientServiceFallbackFactory */ //服务降级:fallbackFactory=DeptClientServiceFallbackFactory.class @FeignClient(value = "MICROSERVICECLOUD-DEPT",fallbackFactory=DeptClientServiceFallbackFactory.class) 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); }
9.2.4、服务降级处理
DeptClientServiceFallbackFactory.java
package com.yjiu.cloud.service; import java.util.List; import org.springframework.stereotype.Component; import com.yjiu.cloud.pojo.Dept; import feign.hystrix.FallbackFactory; @Component // 不要忘记添加,不要忘记添加 public class DeptClientServiceFallbackFactory implements FallbackFactory<DeptClientService>{ @Override public DeptClientService create(Throwable throwable){ return new DeptClientService() { @Override public Dept get(long id) { return new Dept().setDeptno(id).setDname("该ID:" + id + "没有没有对应的信息,Consumer客户端提供的降级信息,此刻服务Provider已经关闭") .setDb_source("no this database in MySQL"); } @Override public List<Dept> list() { return null; } @Override public boolean add(Dept dept) { return false; } }; } }
9.3、Eureka服务注册中心+Ribbon+Feign+Hystrix
9.3.1、Eureka-Server端
9.3.1.1、工程图
9.3.1.2、POM文件
<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> <parent> <groupId>com.yjiu.cloud</groupId> <artifactId>microservicecloud</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>microservicecloud-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>
9.3.1.3、application.yml
server: port: 7001 eureka: instance: hostname: eureka7001.com #eureka服务端的实例名称 client: register-with-eureka: false #false表示不向注册中心注册自己。 fetch-registry: false #false表示自己端就是注册中心,我的职责就是维护服务实例,并不需要去检索服务 service-url: #单机 defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ #设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址(单机)。 defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
9.3.1.4、App主启动类【@EnableEurekaServer】
package com.atguigu.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer // EurekaServer服务器端启动类,接受其它微服务注册进来 public class EurekaServer7001_App { public static void main(String[] args) { SpringApplication.run(EurekaServer7001_App.class, args); } }
9.3.1.5、集群搭建
互相注册,7001注册7002和7003,7002注册7001和7003,同理..
YML: 1、server:port:修改对应的端口号 2、eureka:instace:hostname:修改对应的域名 3、defaultZone: 7001项目上的: defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ 7002项目上的: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7003.com:7003/eureka/ 7003项目上的: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/ 4、注册到Server上的项目,要修改defaultZone:
9.3.2、Eureka-Client端-服务提供者
9.3.2.1、项目图
DeptService已提取到Cloud-API工程
9.3.2.2、 POM
<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> <parent> <groupId>com.yjiu.cloud</groupId> <artifactId>microservicecloud</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>microservicecloud-provider-dept-8001</artifactId> <dependencies> <!-- 引入自己定义的api通用包,可以使用Dept部门Entity --> <dependency> <groupId>com.yjiu.cloud</groupId> <artifactId>microservicecloud-api</artifactId> <version>${project.version}</version> </dependency> <!-- hystrix --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</artifactId> </dependency> <!-- actuator监控信息完善 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- 将微服务provider侧注册进eureka --> <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>junit</groupId> <artifactId>junit</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </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> </dependencies> </project>
9.3.2.3、application.yml
server: port: 8001 mybatis: config-location: classpath:mybatis/mybatis.cfg.xml # mybatis配置文件所在路径 type-aliases-package: com.yjiu.cloud.pojo # 所有Entity别名类所在包 mapper-locations: - classpath:mybatis/mapper/**/*.xml # mapper映射文件 spring: application: name: microservicecloud-dept datasource: type: com.alibaba.druid.pool.DruidDataSource # 当前数据源操作类型 driver-class-name: org.gjt.mm.mysql.Driver # mysql驱动包 url: jdbc:mysql://localhost:3306/cloudDB01?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull # 数据库名称 username: root password: mysqladmin dbcp2: min-idle: 5 # 数据库连接池的最小维持连接数 initial-size: 5 # 初始化连接数 max-total: 5 # 最大连接数 max-wait-millis: 200 # 等待连接获取的最大超时时间 eureka: client: #客户端注册进eureka服务列表内 service-url: #defaultZone: http://localhost:7001/eureka defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/ instance: instance-id: microservicecloud-dept8001 prefer-ip-address: true #访问路径可以显示IP地址 info: app.name: atguigu-microservicecloud company.name: www.atguigu.com build.artifactId: $project.artifactId$ build.version: $project.version$
9.3.2.4、App主启动类【@EnableDiscoveryClient】
package com.atguigu.springcloud; 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 //本服务启动后会自动注册进eureka服务中 @EnableDiscoveryClient //服务发现 @EnableHystrix //启用hystrix public class DeptProvider8001_App { public static void main(String[] args) { SpringApplication.run(DeptProvider8001_App.class, args); } }
9.3.2.5、Controller
package com.yjiu.cloud.controller; @RestController public class DeptController { @Autowired private DeptService service; @Autowired private DiscoveryClient client; @RequestMapping(value = "/dept/add", method = RequestMethod.POST) public boolean add(@RequestBody Dept dept)//****注意@RequestBody { 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(); } }
9.3.2.6、MyBatis配置
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> </configuration>
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.yjiu.cloud.dao.DeptDao"> <select id="findById" resultType="com.yjiu.cloud.pojo.Dept" parameterType="Long"> select deptno,dname,db_source from dept where deptno=#{deptno}; </select> <select id="findAll" resultType="com.yjiu.cloud.pojo.Dept"> select deptno,dname,db_source from dept; </select> <insert id="addDept" parameterType="com.yjiu.cloud.pojo.Dept"> INSERT INTO dept(dname,db_source) VALUES(#{dname},DATABASE()); </insert> </mapper>
DeptDao.java
package com.yjiu.cloud.dao; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.yjiu.cloud.pojo.Dept; @Mapper public interface DeptDao{ public boolean addDept(Dept dept); public Dept findById(Long id); public List<Dept> findAll(); }
DeptServiceImpl.java
package com.yjiu.cloud.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yjiu.cloud.dao.DeptDao; import com.yjiu.cloud.pojo.Dept; import com.yjiu.cloud.service.DeptService; @Service public class DeptServiceImpl implements DeptService{ @Autowired private DeptDao dao; @Override public boolean add(Dept dept){ return dao.addDept(dept); } @Override public Dept get(Long id){ return dao.findById(id); } @Override public List<Dept> list(){ return dao.findAll(); } }
9.3.3、Eureka-Client端-服务消费者
9.3.3.1、项目图
9.3.3.2、POM
<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> <parent> <groupId>com.yjiu.cloud</groupId> <artifactId>microservicecloud-parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>microservicecloud-consumer-dept-80</artifactId> <description>部门微服务消费者</description> <dependencies> <dependency><!-- 自己定义的api --> <groupId>com.yjiu.cloud</groupId> <artifactId>microservicecloud-api</artifactId> <version>${project.version}</version> </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-feign</artifactId> </dependency> <!-- Ribbon相关 --> <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>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> </dependencies> </project>
9.3.3.3、application.yml
server: port: 80 feign: hystrix: enabled: true eureka: client: register-with-eureka: false service-url: defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
9.3.3.4、App主启动类,两种方式
9.3.3.4.1、Ribbon方式(不推荐)【@RibbonClient】
package com.yjiu.cloud; 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; import com.yjiu.myrule.MySelfRule; @SpringBootApplication @EnableEurekaClient //在启动该微服务的时候就能去加载我们的自定义Ribbon配置类,从而使配置生效 @RibbonClient(name="MICROSERVICECLOUD-DEPT",configuration=MySelfRule.class) public class DeptConsumer80_App{ public static void main(String[] args){ SpringApplication.run(DeptConsumer80_App.class, args); } }
9.3.3.4.2、Feign方式【@EnableFeignClients】
package com.yjiu.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; import org.springframework.context.annotation.ComponentScan; @SpringBootApplication @EnableEurekaClient @EnableFeignClients(basePackages= {"com.yjiu.cloud"}) @ComponentScan("com.yjiu.cloud") public class DeptConsumer80_Feign_App{ public static void main(String[] args){ SpringApplication.run(DeptConsumer80_Feign_App.class, args); } }
9.3.3.5、Spring配置类【@LoadBalanced】
package com.yjiu.cloud.cfgbeans; 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; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.RetryRule; @Configuration public class ConfigBean //boot -->spring applicationContext.xml --- @Configuration配置 ConfigBean = applicationContext.xml { @Bean @LoadBalanced//Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端 负载均衡的工具。 public RestTemplate getRestTemplate() { return new RestTemplate(); } @Bean public IRule myRule() { //return new RoundRobinRule(); //return new RandomRule();//达到的目的,用我们重新选择的随机算法替代默认的轮询。 return new RetryRule(); } }
9.3.3.6、Controller(不推荐)【Ribbon+RestTemplate】
package com.yjiu.cloud.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.yjiu.cloud.pojo.Dept; @RestController public class DeptController_Consumer { //private static final String REST_URL_PREFIX = "http://localhost:8001"; private static final String REST_URL_PREFIX = "http://MICROSERVICECLOUD-DEPT"; /** * 使用 使用restTemplate访问restful接口非常的简单粗暴无脑。 (url, requestMap, * ResponseBean.class)这三个参数分别代表 REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。 */ @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); } @SuppressWarnings("unchecked") @RequestMapping(value = "/consumer/dept/list") public List<Dept> list() { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class); } // 测试@EnableDiscoveryClient,消费端可以调用服务发现 @RequestMapping(value = "/consumer/dept/discovery") public Object discovery() { return restTemplate.getForObject(REST_URL_PREFIX + "/dept/discovery", Object.class); } }
9.3.3.7、Controller【接口+Feign】
package com.yjiu.cloud.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.yjiu.cloud.pojo.Dept; import com.yjiu.cloud.service.DeptClientService; @RestController public class DeptController_Consumer{ /**重点区别:之前用restTemplate,现在用接口**/ @Autowired private DeptClientService service; @RequestMapping(value = "/consumer/dept/get/{id}") public Dept get(@PathVariable("id") Long id) { return this.service.get(id); } @RequestMapping(value = "/consumer/dept/list") public List<Dept> list() { return this.service.list(); } @RequestMapping(value = "/consumer/dept/add") public Object add(Dept dept) { return this.service.add(dept); } }
9.3.3.8、切换负载均衡
package com.yjiu.myrule; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.netflix.loadbalancer.IRule; import com.netflix.loadbalancer.RandomRule; @Configuration public class MySelfRule{ @Bean public IRule myRule(){ return new RandomRule();// Ribbon默认是轮询,我自定义为随机 //return new RoundRobinRule();// Ribbon默认是轮询,我自定义为随机 // return new RandomRule_ZY();// 我自定义为每台机器5次 } }
9.4、Zuul
豪猪Hystrix Dashboard
9.4.1、工程图
9.4.2、POM文件
<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> <parent> <groupId>com.atguigu.springcloud</groupId> <artifactId>microservicecloud</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>microservicecloud-zuul-gateway-9527</artifactId> <dependencies> <!-- *****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.atguigu.springcloud</groupId> <artifactId>microservicecloud-api</artifactId> <version>${project.version}</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> </dependencies> </project>
9.4.3、主启动类
package com.yjiu.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableZuulProxy public class Zuul_9527_StartSpringCloudApp { public static void main(String[] args) { SpringApplication.run(Zuul_9527_StartSpringCloudApp.class, args); } }
9.4.4、application.yml
server: port: 9527 spring: application: name: microservicecloud-zuul-gateway eureka: client: service-url: defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka instance: instance-id: gateway-9527.com prefer-ip-address: true zuul: prefix: /atguigu #配合使用,通过http://localhost/atguigu/mydept/consumer/dept/list访问 ignored-services: "*" #禁止通过【服务名】访问 #ignored-services: microservicecloud-dept #禁止通过【服务名】访问:http://localhost/microservicecloud-dept/consumer/dept/list访问 routes: mydept.serviceId: microservicecloud-dept mydept.path: /mydept/** #只有这个,通过http://localhost/mydept/consumer/dept/list访问 info: app.name: atguigu-microcloud company.name: www.atguigu.com build.artifactId: $project.artifactId$ build.version: $project.version$
9.5、分布式配置中心
9.5.1、GitHub上建立配置文件仓库
GitHub建完库,拉取到本地,新建配置文件application.yml,并提交
spring: profiles: active: dev --- spring: profiles: dev #开发环境 application: name: cloud-config-dev --- spring: profile: test application: name: cloud-config-test
9.5.2、Config-Server
9.5.2.1、项目图
9.5.2.2、POM文件
<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> <parent> <groupId>com.yjiu.cloud</groupId> <artifactId>microservicecloud-parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>microservicecloud-config-3344</artifactId> <dependencies> <!-- springCloud Config --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency> <!-- 避免Config的Git插件报错:org/eclipse/jgit/api/TransportConfigCallback --> <dependency> <groupId>org.eclipse.jgit</groupId> <artifactId>org.eclipse.jgit</artifactId> <version>4.10.0.201712302008-r</version> </dependency> <!-- 图形化监控 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- 熔断 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</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.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> </dependencies> </project>
9.5.2.3、App主启动类[@EnableConfigServer]
package com.yjiu.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer; @SpringBootApplication @EnableConfigServer public class Config_3344_StartSpringCloudApp{ public static void main(String[] args){ SpringApplication.run(Config_3344_StartSpringCloudApp.class, args); } }
9.5.2.4、application.yml
server: port: 3344 spring: application: name: cloud-config cloud: config: server: git: uri: https://github.com/yjiu11/cloud-config.git #GitHub上面的git仓库名字
9.5.2.5、测试
http://localhost:3344/application-dev.yml
9.5.3、Config-Client
9.5.3.1、项目图
9.5.3.2、POM
<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> <parent> <groupId>com.yjiu.cloud</groupId> <artifactId>microservicecloud-parent</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <artifactId>config-client-3355</artifactId> <dependencies> <!-- SpringCloud Config客户端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-hystrix</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.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> </dependencies> </project>
9.5.3.3、App主启动类
package com.yjiu.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ConfigClient_3355_StartSpringCloudApp{ public static void main(String[] args){ SpringApplication.run(ConfigClient_3355_StartSpringCloudApp.class, args); } }
9.5.3.4、application.yml
spring: application: name: cloud-config-client
9.5.3.5、bootstrap.yml
spring: cloud: config: name: cloud-config-client #需要从github上读取的资源名称,注意没有yml后缀名 profile: dev #本次访问的配置项 label: master uri: http://localhost:3344 #本微服务启动后先去找3344号服务,通过SpringCloudConfig获取GitHub的服务地址
9.5.3.6、bootstrap.yml与GitHUB建立关联
9.5.3.7、Controller测试
package com.yjiu.cloud.rest; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ConfigClientRest{ @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; } }
9.5.3.8、测试
http://localhost:8201/config 此时8202不能访问,因为dev环境端口8201
修改bootstrap.yml
spring: cloud: config: name: cloud-config-client profile: test #由dev改为test****** label: master uri: http://localhost:3344
http://localhost:8202/config 此时8201不能访问,因为test环境端口8202
来源:https://www.cnblogs.com/yjiu/p/12635740.html