1.为了克服使用RestTemplate进行微服务负载均衡调用的复杂性,springcloud提供了声明式组件-----Feign;Feign是一个基于接口的编程方式,开发者只需要声明接口和配置注解,在调度接口方法时,springCloud就根据配置来调度对应的REST风格的请求,从其他微服务系统中获取数据,使用Feign首先需要在产品微服务中使用Maven引入依赖包:
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId><version>2.2.3.RELEASE</version>
</dependency>
- 然后在springboot的启动文件中添加注解@EnableFeignClients,这个注解代表该项目会启动Feign客户端:
@SpringBootApplication
//@EnableDiscoveryClient
**@EnableFeignClients**
public class LearnProductApplication {public static void main(String[] args) {SpringApplication.run(LearnProductApplication.class, args);}// 初始化RestTemplate@LoadBalanced //多节点负载均衡@Bean(name="restTemplate")public RestTemplate initRestTemplate(){return new RestTemplate();}}
- 然后定义Feign接口:
@FeignClient("user")
public interface UserService {@GetMapping("/user/getUserPo/{id}")public UserPo getUser(@PathVariable("id") Long id);// POST方法请求用户微服务,并使用请求体参数@PostMapping("/user/insert")public Map<String,Object> addUser(@RequestBody UserPo user);// POST方法请求用户微服务,并使用URL参数和请求头参数@PostMapping("/user/update/{userName}")public Map<String,Object> updateName(@PathVariable("userName") String userName, @RequestHeader("id") Long id);
}
- 之后在ProductController中加入UserService接口对象的注入:
@Autowiredprivate UserService userService;
- 使用Feign调度用户微服务的REST端点:
@GetMapping("/feign")public List<UserPo> testFeign(){logger.info("testFeign");List<UserPo> list=new ArrayList<>();UserPo user=null;for (int i=0;i<10;i++){Long id=(long)(i+1);user=userService.getUser(id);list.add(user);}return list;}
- 参考项目示例:https://gitee.com/manongfaner/cloud-maven-learn