意义在于减少重复代码量。实现方式如下:
//请求接口
public interface DiscoveryClient {
@RequestMapping("/ping/{hello}")
String infoForServiceId(@PathVariable String hello);
}
//feign客户端接口
@FeignClient(name = "discovery-client")
public interface DiscoveryFeignClient extends DiscoveryClient{
}
//不使用继承特性时的controller及方法
@RequestMapping("/test/feign")
@RestController
public class TestFeignController {
@Autowired
DiscoveryFeignClient discoveryClient;
@Autowired
ZuulClient zuulClient;
//不使用继承时,我们需要手工加上 @RequestMapping("/pingByServiceId/{hello}")
@RequestMapping("/pingByServiceId/{hello}")
public String infoForServiceId(@PathVariable String hello){
String str = discoveryClient.infoForServiceId(hello);
return str;
}
}
//使用feigin继承特性的Controller
@RequestMapping("/test/feign")
@RestController
public class TestFeignInheritanceController implements DiscoveryClient {
@Autowired
DiscoveryFeignClient discoveryClient;
//使用继承时,不需要加@RequestMapping("/ping/{hello}") 访问此方法时,使用ip/test/feign/ping/参数 的方式访问
@Override
public String infoForServiceId(@PathVariable String hello){
String str = discoveryClient.infoForServiceId(hello);
return str;
}
}
使用继承的方式时,控制器中的方法可以继承接口中的requestMapping,不使用继承的时候需要手工定义。
经测试实现类方法中的参数注解@PathVariable、@RequestMapping、@RequestParam、@RequestHeader、@RequestBody都可以不添加。
@RequestMapping("/test/feign")
@RestController
public class TestFeignInheritanceController implements DiscoveryClient {
@Autowired
DiscoveryFeignClient discoveryClient;
/**
* @Title:
* @Description: 测试根据服务name进行访问
* @param
* @return
* @author huxx
* @date 2019/11/8 下午3:24
* @update
*/
@Override
public String infoForServiceId( String hello,String name,String age, Map<String,String> params){
String str = discoveryClient.infoForServiceId(hello,name,age,params);
return str;
}
}
/**
* @Title: DiscoveryClient
* @Description: 测试使用feign的方式引用discovery-client服务
* @author huxx
* @date 2020/3/23 下午4:19
* @update
*/
public interface DiscoveryClient {
@RequestMapping("/ping/{hello}")
String infoForServiceId(@PathVariable String hello, @RequestParam("name") String name, @RequestHeader("age") String age,@RequestBody Map<String,String> params);
}
feign的接口不可再继承其它interface,否则报错如下:Only single-level inheritance supported: RefactTestFeignService在SpringCloud中Feign支持继承,但是不支持多层继承
(他人结论,未亲自验证)