Spring Cloud OpenFeign(客户端负载均衡)

2020-11-27  本文已影响0人  机灵鬼鬼

第一步、引入Fegin特性

 <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

第二步、创建接口

Fegin: 接口+注解

/**
 * 使用Feign的注解+接口的形式来进行服务调用
 */
@FeignClient(value="TAKEOUT3-PROVIDER-PRODUCT") //feign与注册入Eureka的微服务建立连接
public interface DataChannelClientService {
    //这里映射真正的业务DataChannelController入口地址:“/channel/{id}”
    @RequestMapping(method = RequestMethod.GET, value = "/channel/{id}")
    public DataChannel getDataChannelById(@PathVariable("id")int id);

    @RequestMapping(method = RequestMethod.POST, value = "/channel")
    public DataChannel insertDataChannel(DataChannel dataChannel) throws Exception;

    @RequestMapping(method = RequestMethod.POST, value = "/channel/update")
    public int updateDataChannel(DataChannel dataChannel) throws Exception;

    @RequestMapping(method = RequestMethod.POST, value = "/channel/delete")
    public int deleteDataChannel(DataChannel dataChannel) throws Exception;
}

第三步、创建Feign的微服务

@RestController
public class DataChannelController_Feign {

    @Autowired
    private DataChannelClientService service;

    @RequestMapping(value = "/consumer/channel/{id}",method = RequestMethod.GET)
    public DataChannel getDataChannelById(@PathVariable("id") int id) {
        return service.getDataChannelById(id);//去找微服务的入口地址
    }
    @RequestMapping(value = "/consumer/channel",method = RequestMethod.POST)
    public DataChannel insertDataChannel(DataChannel dataChannel) throws Exception {
        return service.insertDataChannel(dataChannel);
    }
    @RequestMapping(value = "/consumer/channel/update",method = RequestMethod.POST)
    public int updateDataChannel(DataChannel dataChannel) throws Exception {
        int cnt=0;
        try {
            cnt= service.updateDataChannel(dataChannel);
        } catch (Exception e) {
            e.printStackTrace();
//            throw  new MyException("2003","更新渠道错误");
        }
        return cnt;
    }
    @RequestMapping(value = "/consumer/channel/delete",method = RequestMethod.POST)
    public int deleteDataChannel(DataChannel dataChannel) throws Exception {
        int cnt=0;
        try {
            cnt= service.deleteDataChannel(dataChannel);
        } catch (Exception e) {
            e.printStackTrace();
//            throw  new MyException("2001","删除渠道错误");
        }
        return cnt;
    }
}

第四步、加入yml

server:
  port: 80
spring:
  cloud:
    loadbalancer:
      ribbon:
        enabled: false
feign:
  client:
    config:
      default:
        connectTimeout: 5000 #连接超时时间
        readTimeout: 5000    #请求与响应的时间间隔阈值
eureka:
  client:
    serviceUrl:
      defaultZone: http://xx3:7001/eureka/,http://xx2:7001/eureka/,http://xx1:7001/eureka/

第五步、测试


image.png
上一篇 下一篇

猜你喜欢

热点阅读