【SpringCloud】使用Feign远程调用

 

原来的请求方式

Application启动类开启请求模板

@Bean
@LoadBalanced
public RestTemplate restTemplate(){
    return new RestTemplate();
}

 

1.载入请求模板

    @Autowired
    private RestTemplate restTemplate;

 

2.请求

String url = "http://userservice/user/" + orderPojo.getUserId();
UserPojo user = restTemplate.getForObject(url, UserPojo.class);

 


 

使用Feign客户端请求

载入依赖:

版本号跟随Springcloud

<!--        Feign客户端请求-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.2.5.RELEASE</version>
        </dependency>

 

 

1.开启

启动类中加入注解 自动装配

@EnableFeignClients

 

2.编写请求接口

@FeignClient里面写服务名称

GetMapping写请求方式和服务的请求地址

@FeignClient("userservice")
public interface UserClient {

    @GetMapping("/user/{id}")
    UserPojo findById(@PathVariable("id") Integer id);

}

 

 

3.使用

载入上面写的接口

直接调用

@Autowired
private UserClient userClient;


@GetMapping("/order/{id}")
public OrderPojo test1(@PathVariable("id")Integer id){
    LambdaQueryWrapper<OrderPojo> wp = new LambdaQueryWrapper<OrderPojo>().eq(OrderPojo::getId, id);
    OrderPojo orderPojo = orderMapper.selectOne(wp);
    UserPojo user = userClient.findById(orderPojo.getUserId());

    orderPojo.setUserPojo(user);
    return orderPojo;
}

 

 

补充:Feign优化

Feign默认是URLconnection,不支持连接池,可以替换为Apache HttpClient或者OkHttp来配置连接池

 

下面是使用Apache HttpClient,Spring默认自带管理的

1.载入依赖包

<!--        Feign HttpClient依赖,加连接池功能-->
        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-httpclient</artifactId>
            <version>10.0.0</version>
        </dependency>

 

application.yml配置项里面修改

feign:
  httpclient:
    enabled: true # 开启httpclient
    max-connections: 200 #最大连接数
    max-connections-per-route: 50 #单个路径的最大连接数

 

posted @ 2023-02-24 21:16  Hello霖  阅读(57)  评论(0)    收藏  举报