Spring-Cloud Feign 使用
2018-04-26 本文已影响0人
晴天mk1992
前提:服务端和客户端需要集成注册中心
一、服务端
1、声明接口
@CrossOrigin
@RestController("myTestController")
@RequestMapping(value = "/server")
public class TestController {
@RequestMapping(value = "/forward/{serviceCode}",
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
method = RequestMethod.POST)
public Result index(HttpServletRequest request,@PathVariable("serviceCode") String serviceCode, @RequestBody Map<String,Object> params);
}
二、客户端
1、依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.4.4.RELEASE</version>
</dependency>
2、启动配置
在启动Application类加上@EnableFeignClients
注解
3、创建Client接口
@Component
@FeignClient("application-server")
public interface ClientFeignClient {
@RequestMapping(value = "/server/forward/{serviceCode}",
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE,
method = RequestMethod.POST)
public Result forwardReq(@PathVariable("serviceCode") String serviceCode, @RequestBody Map<String,Object> params);
}
注:@FeignClient("application-server")中要配置接口提供端的应用名称(application.properties的application.name),方法的 @RequestMapping和需要调用的接口的全路径相同。
4、Controller或Service调用客户端方法
1)声明
@Autowired
ClientFeignClient clientFeignClient;
2)调用方式:
clientFeignClient.forwardReq(serviceCode,params);
5、遇到的问题
Caused by: java.lang.IllegalStateException: PathVariable annotation was empty on param 0.
原因:
@PathVariable("serviceCode") String 中漏写了参数名称