微服務的服務消費,一般是使用 feign 和 rebion 調用服務提供,進行服務的消費,本文將實戰使用代碼講解服務的消費。
微服務環境的搭建
創建一個 springboot 項目,springboot 是將服務進行拆分的一個最小服務單位。
添加 maven 依賴
- 基本的maven依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- rebion 依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
- feign 依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
feign依賴包含rebion依賴,如果想同時使用 feign 和 rebion 依賴,只需要引用feign 即可。
添加application.yml
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
添加Appcation.java啟動類
@SpringBootApplication
//將服務注冊到注冊中心
@EnableDiscoveryClient
//掃描和注冊feign客戶端bean定義
@EnableFeignClients
public class NacosConsumeApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConsumeApplication.class, args);
}
}
其中 @EnableDiscoveryClient 將服務注冊到注冊中心,@EnableFeignClients 掃描和注冊feign客戶端bean定義。fegin bean定義是 @FeignClient。
服務調用 : feign 和 ribbon
1. feign
- 創建feign客戶端
@FeignClient(value = "service-provider")
public interface ProductClient {
@GetMapping("/hello")
String product(@RequestParam("name") String name);
}
這里 @FeignClient 就是創建bean 給 @EnableFeignClients 掃描的注冊。 @FeignClient 里面的配置 value 對應的是服務提供者的服務名稱,@GetMapping里面的value對應服務提供者的 @GetMapping 路徑。
這樣做的好處是這里直接配置好路徑和服務名稱,不需要調用方做任何的配置。
- 創建請求調用 feign客戶端
@RestController
public class FeignController {
//這個錯誤是編譯器問題。 因為這個Bean是在程序啟動的時候注入的,編譯器感知不到,所以報錯。
@Autowired
private ProductClient productClient;
@GetMapping("/feign")
public String feign(String name){
return productClient.product(name);
}
}
2. rebion
- 配置 RestTemplate bean
@Configuration
public class RibbonConfig {
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
- 調用服務
@RestController
public class RibbonController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/ribbon")
public String ribbon(String name){
String result = restTemplate.getForObject("http://service-provider/hello?name="+name,String.class);
return result;
}
}
feign 和 rebion 優缺點
- feign 配置比較簡單明了,配置好了 FeignClient,直接調用即可,不過后續有多余的配置。
- rebion每次都需要配置請求路徑,它的優點在於直接調用即可,不要單獨配置客戶端。