Springcloud 系列之feign负载均衡

feign 的使用

Feign是声明性的web服务客户端。它使编写web服务客户端更加容易。要使用Feign,请创建一个接口并对其进行注释。它具有可插入的注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插拔编码器和解码器。Spring Cloud添加了对Spring MVC注释的支持,并支持使用Spring Web中默认使用的同一HttpMessageConverters。Spring Cloud集成了Ribbon和Eureka以在使用Feign时提供负载平衡的http客户端。

1、创建feign的微服务模块

在前两篇博客的基础上,根据参考microservicecloud-consumer-dept-80,新建microservicecloud-consumer-dept-feign。

1、引入feign 的jar 包
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
2、feign 的配置文件
server:
  port: 80

eureka:
  client:
    service-url:
      defaultZone: eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka,http://eureka7003.com:7003/eureka

feign:
  hystrix:
    enabled: ture #feign开启hystrix,使其在api模块中的服务降级,统一处理熔断
3、新建DeptClientService接口并添加@feignClient注解
//Feign的面向接口编程,在注解的中指定服务提供者的名字
@FeignClient(value = "STUDY-SPRINGCLOUD-DEPT")
public interface DeptClientService {
        @RequestMapping(value = "/dept/add",method = RequestMethod.GET)
        public boolean add( DeptEntity deptEntity);
    
        @RequestMapping(value = "/dept/findById/{deptNo}",method = RequestMethod.GET)
        public DeptEntity findById(Long deptNo);
    
        @RequestMapping(value = "/dept/findAll",method = RequestMethod.GET)
        public List findAll();
        @FeignClient(value = "STUDY-SPRINGCLOUD-DEPT")
}
4、修改feign服务中的controller层代码
@RestController
  public class DeptConsumerController {
      @Autowired
      private DeptClientService deptClientService;
      @RequestMapping(value = "/consumer/dept/add")
      public boolean add( DeptEntity deptEntity){
          //三个参数:url,requestMap ResponseBean.class
          return  deptClientService.add(deptEntity);
      }
      @RequestMapping("/consumer/dept/findById/{deptNo}")
      public DeptEntity findById(Long deptNo){
          //三个参数:url,requestMap ResponseBean.class
          return deptClientService.findById(deptNo);
      }
      @RequestMapping("/consumer/dept/findAll")
      public List findAll(){
          //三个参数:url,requestMap ResponseBean.class
          return  deptClientService.findAll();
      }
  }
5、修改feign的启动类
@SpringBootApplication
@EnableEurekaClient
/**
 * 在启动该微服务式是能去加载我们定义的Feign配置类
 */
@EnableFeignClients(basePackages = "com.msun.springcloud")
@ComponentScan("com.msunn.springcloud")
public class DeptConsumerFeignApp {
    public static void main(String[] args) {
        SpringApplication.run(DeptConsumerFeignApp.class,args);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值