1.在pom文件添加相关依赖
<dependencies> <!-- web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- common --> <dependency> <groupId>cn.kgc</groupId> <artifactId>hello-sc-2109-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <!-- eureka 客户端依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- actuator监控信息完善 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <!-- ribbon --> <!-- <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency>--> <!-- openfeign,已经内置啦ribbon --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- hystrix依赖 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-hystrix</artifactId> </dependency> </dependencies>
2.yml里面添加相关配置 default的用户名跟密码是eureka里面的yml相关配置提供的
server: port: 8888 spring: application: name: hello-consumer jackson: date-format: yyyy-MM-dd time-zone: GMT+8 logging: level: cn.kgc: debug eureka: client: service-url: defaultZone: http://admin:1234@localhost:7001/eureka/,http://admin:1234@localhost:7002/eureka/ register-with-eureka: true fetch-registry: true instance: instance-id: ${spring.application.name}-${server.port} prefer-ip-address: true # 指定负载均衡策略 HELLO-PROVIDER: ribbon: NFLoadBalancerRuleCl assName: com.netflix.loadbalancer.RandomRule feign: hystrix: enabled: true #启用断路器
3.启动类 添加注解
@SpringBootApplication @EnableEurekaClient//注册到EurekaServer @EnableFeignClients//@EnableFeignClients注解告诉框架扫描所有使用注解@FeignClient定义的feign客户端,并把feign客户端注册到IOC容器中。 @EnableHystrix //让断路器可用
4.service.feign. 添加crud接口
@FeignClient(value = "HELLO-PROVIDER",fallback = EmpFeignServiceHystrix.class)//微服务名称 public interface EmpServiceFeign { @GetMapping("/emp/list") public Result<List<Emp>> getEmpList(); @GetMapping("/emp/{id}") public Result<Emp> getEmpById(@PathVariable("id") Integer id); @PostMapping("/emp") public Result<Emp> addEmp(@RequestBody Emp emp); @PutMapping("/emp") public Result<Emp> updateEmp(@RequestBody Emp emp); @DeleteMapping("/emp/{id}") public Result<Object> deleteEmpById(@PathVariable("id") Integer id); }
5.service.hystrx. 实现curd接口
//容错处理 @Component public class EmpFeignServiceHystrix implements EmpServiceFeign { @Override public Result<List<Emp>> getEmpList() { return Result.fail(20005,"员工列表接口繁忙"); }
}
6.配置类common.config
@Configuration public class WebConfig { @Bean @LoadBalanced//开启负载均衡的功能 //@LoadBalanced注解,我们在使用这个注解后,就能在调用其他微服务的时候,通过服务实例名称就能进行调用其他的微服务,而不是直接把要调用的微服务的ip和端口号写死在代码当中。 public RestTemplate restTemplate(){ return new RestTemplate(); } }