基本的 consumer 已經很複雜了,所以複製 consumer 成為一個新 module,刪除ribbon相關的內容(兩個 class 和 @RibbonClien,連 ConfigRestTemplate也不要了)
1.api 和 consumerFeign 的 pom
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
※這樣才有 @FeignClient 和 @EnableFeignClients 可用
2.
@FeignClient("PROVIDER1")
public interface MyService {
@GetMapping("/testGet")
ApiBean get();
}
※@FeignClient 指定想訪問的 spring.application.name
3.
@SpringBootApplication
@ComponentScan("controller")
@EnableEurekaClient
@EnableFeignClients("service")
public class ConsumerFeignMain {
public static void main(String[] args) {
SpringApplication.run(ConsumerFeignMain.class, args);
}
}
※@EnableFeignClients 指定 api 裡的包路徑,只要錯了,啟動時就會出現 A component required a bean of type 'service.MyService' that could not be found.
4.
@RestController
public class ConsumerController {
// private static final String PROVIDER_URI = "http://localhost:9001";
/* private static final String PROVIDER_URI = "http://"+ "provider1".toUpperCase(); // 網址列不分大小寫,但還是以 eureka 為準的好
@Resource
private RestTemplate restTemplate;
@GetMapping("/xxx")
public ApiBean get() {
return restTemplate.getForObject(PROVIDER_URI + "/testGet", ApiBean.class);
}
*/
@Resource
private MyService myService;
@GetMapping("/xxx")
public ApiBean get() {
return myService.get();
}
}
※使用 feign 後,可以不用寫服務名
※預設是輪詢算法,可以將上一篇的 MyCustomRibbonRule 複製過來,改變自己想要的算法或內鍵的其他算法
沒有留言:
張貼留言