Feign调用技巧

在实际的微服务开发中,如果用到Feign,可能会针对不同微服务定义不同的FeignClient,比如有一个User服务,客户端Feign调用一般写法如下:

@FeignClient(name = "user-service")
public interface UserFeign {

    @RequestMapping(method = RequestMethod.POST, value = "/api/user")
    ResponseEntity> addUser(@RequestBody Map body);

    @RequestMapping(method = RequestMethod.GET, value = "/api/user")
    ResponseEntity> getUserList( @RequestParam Map paramMap);

    @RequestMapping(method = RequestMethod.PUT, value = "/api/user")
    ResponseEntity updateUser(@RequestBody JSONObject body);

    @RequestMapping(method = RequestMethod.DELETE , value = "/api/user")
    ResponseEntity deleteUser(@PathVariable("id") String id);

    ....
}

或者是

@FeignClient(name = "user-service" url = 网关地址+"/user-service")
public interface UserFeign {

    @RequestMapping(method = RequestMethod.POST, value = "/api/user")
     ResponseEntity> addUser(@RequestBody Map body);

      ....

其实还有更通用的写法

@FeignClient(
    value = "ZUUL网关地址",
    fallback = XXXCallback.class
)
public interface CommonFeign {
    @RequestMapping(
        method = {RequestMethod.POST},
        value = {"/{appName}/{apiUrl}"}
    )
    JsonResult postWithParam(@PathVariable("appName") String appName, @PathVariable("apiUrl") String apiUrl, @RequestBody Map body);
    @RequestMapping(
        method = {RequestMethod.GET},
        value = {"/{appName}/{apiUrl}"}
    )
    JsonResult commonGet(@PathVariable("appName") String var1, @PathVariable("apiUrl") String var2);
}

说明
1、appName参数指的微服务名字

spring.application.name=user-service

2、apiUrl参数为Api接口地址

/api/user

3、@FeignClient中的value属性要指定zuul网关服务名

@FeignClient(
    value = "zuul网关服务名",
    fallback = XXXCallback.class
)

可以在Eureka服务注册中心找到ZUUL服务名

微信图片_20180824134950.png

你可能感兴趣的:(Feign调用技巧)