1、jar包依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、启动类添加注解
若A调B服务,则A服务启动类需要添加注解
@EnableFeignClients (为了扫描feign接口)
属性:
basePackageClasses 扫描类
basePackages 扫描包
@EnableFeignClients(basePackageClasses = RegistryService.class, basePackages = “com.wzj.feign”)
3、调用方式
A调B
第一种方式,直接url调用
name是为B服务起的名字,必输。
@FeignClient(url = "http://192.168.20.11:8081", name = "web-socket-api", configuration = FeignConfiguration.class)
public interface WebSocketManageClient {
@RequestMapping(value = "/message", method = RequestMethod.POST)
void sendMessage(@RequestParam(value = "message") String message);
}
使用时
@Autowired
private WebSocketManageClient webSocketManageClient;
webSocketManageClient.sendMessage(message);
第二种方式,使用注册中心
value的值为B服务注册到注册中心的服务名,和name作用一样。name 和value必须存在一个。
@FeignClient(value = "user-server")
public interface UserFeign {
@GetMapping(value = "/user/getUserById")
User getUserById(@RequestParam("id") String id) throws Exception;
4、问题点
曾经在这里遇到个问题,@RequestParam 和@PathVariable 没有使用value属性报错
错误:Feign PathVariable annotation was empty on param 0
例子:
@RequestParam String id
@PathVariable String id
使用vlue属性,给默认名后就可以了
@RequestParam(value = “id”) String id 或者@RequestParam(id) String id
@PathVariable(value = “id”) String id 或者@PathVariable(id) String id