Spring-Cloud Feign 使用

前提:服务端和客户端需要集成注册中心
一、服务端
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 中漏写了参数名称
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容