SpringCloud 使用Feign访问服务

Feign简介:

  声明式的Rest  WEB 服务的客户端, https://github.com/OpenFeign/feign。Spring Cloud 提供了Spring-cloud-starter-openfeign的支持

Feign的简单使用

  pom文件

        
      
        1.8
        Greenwich.SR1
    
        
    
            
            org.springframework.cloud
            spring-cloud-starter-openfeign
        

        
            io.github.openfeign
            feign-httpclient
        


        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        


        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        

  开启Feign的支持

    @EnableFeignClients

@SpringBootApplication
@Slf4j
@EnableFeignClients // 开启Feign支持
public class CustomerServiceApplication {}

注入CloseableHttpClient

  

@Bean
    public CloseableHttpClient httpClient() {
        return HttpClients.custom()
                .setConnectionTimeToLive(30, TimeUnit.SECONDS)
                .evictIdleConnections(30, TimeUnit.SECONDS)
                .setMaxConnTotal(200)
                .setMaxConnPerRoute(20)
                .disableAutomaticRetries()
                // 存活策略
                .setKeepAliveStrategy(new CustomConnectionKeepAliveStrategy())
                .build();
    }

//CustomConnectionKeepAliveStrategy
public class CustomConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy {
    private final long DEFAULT_SECONDS = 30;

    @Override
    public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
        return Arrays.asList(response.getHeaders(HTTP.CONN_KEEP_ALIVE))
                .stream()
                .filter(h -> StringUtils.equalsIgnoreCase(h.getName(), "timeout")
                        && StringUtils.isNumeric(h.getValue()))
                .findFirst()
                .map(h -> NumberUtils.toLong(h.getValue(), DEFAULT_SECONDS))
                .orElse(DEFAULT_SECONDS) * 1000;
    }
}

 

定义Feign接口

@FeignClient(name = "my-service", contextId = "order")
public interface OrderService {
    @GetMapping("/order/{id}")
    Order getOrder(@PathVariable("id") Long id);

    @PostMapping(path = "/order/", consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    Order create(@RequestBody NewOrderRequest newOrder);
}

使用Feign

/**注入刚刚定义的OrderService*/
    @Autowired
    private OrderService orderService;

// 使用

List coffees = coffeeService.getAll();

// 传对象参数
NewOrderRequest orderRequest = NewOrderRequest.builder()
                .customer("Li Lei")
                .items(Arrays.asList("capuccino"))
                .build();
        Order order = orderService.create(orderRequest);


// 单个参数
Order order = orderService.getOrder(id);

 

你可能感兴趣的:(SpringCloud 使用Feign访问服务)