spring cloud feign 接口继承以及参数传递的问题
2024-09-24 06:29:51 阅读次数:28
springcloud
spring cloud feign 接口继承以及参数传递的问题
1. 优势
可以使用maven 进行访问,实现代码的共享,减少跨服务调用服务编写的问题
2. 使用
定义接口
publicinterfaceIUserService{
@RequestMapping(method =RequestMethod.GET, value ="/users/app",headers={"tenantid"})
@ApiOperation(value ",httpMethod ="GET", response =User.class,notes ="请保证传入字段正确")
User getUser(@RequestParam("id")String id,@RequestHeader("tenantid")String tenantid);
@RequestMapping(method =RequestMethod.GET, value ="/users/app2")
User getUser2();
@RequestMapping(method =RequestMethod.GET, value ="/users/app3")
User getUser3();
@RequestMapping(method =RequestMethod.POST, value ="/users/app3")
User getUser4(@RequestBodyUser users);
}
spring mvc rest 接口实现
-
@RestController
publicclassUserServiceFeignControllerimplementsIUserService{
-
@Autowired
privateUserserviceImpl userserviceImpl;
@Override
publicUser getUser2(){
// TODO Auto-generated method stub
return userserviceImpl.getUser2();
}
-
@Override
publicUser getUser3(){
// TODO Auto-generated method stub
return userserviceImpl.getUser3();
}
-
@Override
publicUser getUser(String id,@RequestHeader("tenantid")String tenantid){
// TODO Auto-generated method stub
return userserviceImpl.getUser(id, tenantid);
}
-
@Override
publicUser getUser4(User users){
// TODO Auto-generated method stub
return users;
}
-
}
feign 跨服务调用
@FeignClient
publicinterfaceIFeignUserServiceextendsIUserService{
-
}
注解
@SpringBootApplication
@EnableFeignClients()
publicclassApplication{
-
publicstaticvoid main(String[] args){
SpringApplication.run(Application.class, args);
}
}
调用
@RestController
publicclassUserCacheController{
-
@Autowired
privateIFeignUserService userservice;
@RequestMapping(value ="/demo1", method =RequestMethod.GET)
publicObject importUser(String id,@RequestHeader("tenantid")String tenantid)throwsExecutionException{
return userservice.getUser(id,tenantid);
}
}
3. 注意问题
尽管使用接口继承,但是还是会发现部分参数是没法继承的类似 header 解决方法
调整rest 实现接口方法的签名,如下:
@Override
publicUser getUser(String id,@RequestHeader("tenantid")String tenantid){
// TODO Auto-generated method stub
return userserviceImpl.getUser(id, tenantid);
}
版权声明:本文内容来自第三方投稿或授权转载,原文地址:https://blog.51cto.com/rongfengliang/3119532,作者:rongfengliang,版权归原作者所有。本网站转在其作品的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如因作品内容、版权等问题需要同本网站联系,请发邮件至ctyunbbs@chinatelecom.cn沟通。
上一篇:003_服务拆分和远程调用【注册RestTemplate】
下一篇:Windows 计算机加入域和登录域