feign是一款Netflix开源的声明式、模板化的http客户端,它能够更加便捷、优雅的调用http api;SpringCloud对Netflix的feign进行了加强,使其支持spring并整合了ribbon、eureka以提供负载均衡的http调用。spring
一、引入openfeign依赖api
1 <dependency> 2 <groupId>org.springframework.cloud</groupId> 3 <artifactId>spring-cloud-starter-openfeign</artifactId> 4 </dependency>
二、启动类加上feign注解(须要eureka的支持,因此此模块首先须要为eureka客户端)app
)第一种,针对类扫描feign api负载均衡
@EnableFeignClients(clients = {Xxx1.class, Xxx2.class})spa
)第二种,针对包扫描feign apicode
@EnableFeignClients(basePackages = {"com.xxx.xxx"})blog
三、定义feign api接口
feign api只需与模块的api保持一致就能够了get
)模块:模板
1 @RestController 2 @RequestMapping("/ad") 3 public class AdApi { 4 5 @GetMapping("/getUserAd/{account}") 6 public String getUserAd(@PathVariable(name = "account") String account) { 7 return "这是" + account + "的广告"; 8 } 9 }
)feign api:
1 @FeignClient(name = "ad-model") 2 public interface AdRemoteService { 3 4 @GetMapping("/ad/getUserAd/{account}") 5 String getUserAd(@PathVariable(name = "account") String account); 6 }
四、调用
调用方式很简单,就像调用方法同样就能够了
1 @Autowired 2 private AdRemoteService adRemoteService; 3 4 @GetMapping("/login/{account}/{password}") 5 public String login(@PathVariable String account, @PathVariable String password) { 6 UserDTO userDTO = USER_INFO.get(account); 7 if (userDTO == null) { 8 return "FAILED"; 9 } 10 11 boolean result = userDTO.getPassword().equalsIgnoreCase(password); 12 if (!result) { 13 return "FAILED"; 14 } 15 16 // 调用广告接口 17 String adResult = adRemoteService.getUserAd(account); 18 System.err.println(adResult); 19 20 return "SUCCESS"; 21 }