Java工程師之微服務SpringCloud Feign 技術分享

Java工程師之微服務SpringCloud Feign 技術分享

一、使用Feign

Feign 提供聲明式REST調用。一開始我們還在懊惱,dubbo都已經提供了配置式的服務調用了,為什麼SpringCloud沒有相應的解決方案?有SpringCloud提供了Feign聲明式事務,使用Feign有個非常大的好處就是,只要你屬性SpringMVC的annotation配置,Feign就沒有什麼學習成本。

事不宜遲,我們首先將Feign整合到我們的微服務當中:

<dependency>
<groupid>org.springframework.cloud
<artifactid>spring-cloud-starter-feign

之前的筆記中,用戶服務系統提供了二個接口,第一個接口是查詢用戶、第二個是添加用戶。以下我們就在商品服務中通過Feign整合兩個API

首先我們需要在配置類當中打上@EnableFeignClients

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class ProductsystemApplication {

然後我們創建一個UserFeignClient接口:

@FeignClient(name = "tony-mall-provider-user")
public interface UserFeignClient {
@GetMapping("/user/getUserById/{id}")
User getUserById(@PathVariable("id") int id);
@PutMapping("/user/add")
User addUser(@RequestParam("username") String username, @RequestParam("password")String password,@RequestParam("balance") long balance);
}

接口上面使用了@FeignClient annotation 標記目標的微服務,然後創建相關的方法聲明。或許你已經注意到,所有的操作跟我們SpringMVC中的annotation一模一樣。不過需要注意的是,方法的參數默認是使用@RequestBody進行交換的,所以如果我們希望使用普通的參數傳參,還需要打上SpringMVC的@RequestParam annotation。

之後在我們調用的service層或者是controller層 直接注入UserFeignClient。由於演示我就不劃分業務層和服務層了。

@RestController
public class ProductController {
@Autowired
private ProductRepository productRepository;
@Autowired
private UserFeignClient userFeignClient;

@GetMapping("/getProductByFeign/{productId}/userId/{userId}")
public Map<string> getProductByFeign(@PathVariable int productId, @PathVariable int userId) {
Map<string> map = new HashMap<>();
User user = this.userFeignClient.getUserById(userId);
Product product = this.productRepository.getByProductId(productId);
map.put("user", user);
map.put("product", product);
return map;
}
}

事實上Feign提供了自己的annotation配置,但是如果習慣使用SpringMVC的你,一定會和筆者一樣選擇如上的配置。

二、Feign壓縮

feign.compression.request.mime-types=text/xml,application/xml,application/json
feign.compression.request.min-request-size=2024

mime-types 指定壓縮的類型,min-reqest-size指定壓縮的閾值。

三、Feign日誌

在配置類中配置Feign的日誌級別:

@Bean
public Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}

使用application.properties指定某個接口的日誌級別:

logging.level.com.tony.mall.rest.UserFeignClient=DEBUG


分享到:


相關文章: