1. 添加feign依赖包。
<!-- Feign 相关支持 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
</dependency>
2. 因为Feign是一个声明式WebService客户端。使用Feign能让编写Web Service客户端更加简单,它的使用方法就是定义一个接口,然后在上面添加注解,所以首先创建一个接口,并添加注解声明。
@FeignClient(value = "XXXXXXX(服务提供者名称)")
public interface UserClientService {
@GetMapping("/user/{userId}")
JsonData get(@PathVariable("userId") Long userId);
@GetMapping("/user/list")
JsonData list();
}
3. 修改consumer的controller,使用注入Service的方式实现访问提供者。
@RestController
@RequestMapping("/consumer/user")
public class UserControllerConsumer {
@Autowired
private UserClientService userClientService;
@GetMapping("/{userId}")
public JsonData get(@PathVariable("userId") Long userId) {
return userClientService.get(userId);
}
@GetMapping("/list")
public JsonData selectList() {
return userClientService.list();
}
}
4.修改application启动类,添加开启feign客户端的注解。
@EnableFeignClients(basePackages = {"com.xxx.xxx"})
警告:Feign坑!
首先,我以前写controller接口的时候,对于url上带有参数的接口,在方法中习惯类似 @PathVariable 这样的简写,而不是像 @PathVariable(“userId”) 这样写全,以前没有遇到任何的问题。直到写Feign的时候,在Service中的简写了,然后就报错,找了很久原因,才发现必须要声明参数写全,写代码不要偷懒啊!
错误写法:
@FeignClient(value = "XXXXXXX(服务提供者名称)")
public interface UserClientService {
@GetMapping("/user/{userId}")
JsonData get(@PathVariable Long userId);
@GetMapping("/user/list")
JsonData list();
}
正确写法:
@FeignClient(value = "XXXXXXX(服务提供者名称)")
public interface UserClientService {
@GetMapping("/user/{userId}")
JsonData get(@PathVariable("userId") Long userId);
@GetMapping("/user/list")
JsonData list();
}