前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring boot 内部服务调用 (FeignClient)

Spring boot 内部服务调用 (FeignClient)

作者头像
Java架构师必看
发布2021-11-25 09:47:55
1.2K0
发布2021-11-25 09:47:55
举报
文章被收录于专栏:Java架构师必看

Eureka 注册的服务之间互相调用

1.请求方

启动类添加注解,扫描Eureka 中的全部服务

  1. @SpringBootApplication
  2. @EnableEurekaClient
  3. @EnableFeignClients
  4. public class LoginServiceApplication {
  5. public static void main(String[] args) {
  6. new SpringApplicationBuilder(LoginServiceApplication.class).web(true).run(args);
  7. }
  8. }

pom.xml 添加包 (版本号 根据实际选择)

  1. <dependency>
  2. <groupId>org.springframework.cloud</groupId>
  3. <artifactId>spring-cloud-starter-feign</artifactId>
  4. <version>1.4.6.RELEASE</version>
  5. </dependency>

创建接口类

  1. @FeignClient(name="hello-service") //spring service name
  2. public interface FeignVehicle {
  3. @RequestMapping(value="/hello", method = RequestMethod.GET)
  4. @ResponseBody
  5. public List<Map> hello(@RequestParam Map<String,String> params);
  6. }

实现类注入此接口类

  1. @Autowired
  2. FeignVehicle feignVehicle;

使用的时候直接按照正常调用方式即可

  1. Map<String,String> map = new HashMap<String, String>();
  2. feignVehicle.hello(map);

跨服务调用的时候出现token信息取不到,在发送方添加拦截器

  1. @Configuration
  2. public class FeignConfiguration {
  3. @Bean
  4. public RequestInterceptor requestInterceptor() {
  5. return new RequestInterceptor() {
  6. @Override
  7. public void apply(RequestTemplate template) {
  8. ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
  9. .getRequestAttributes();
  10. HttpServletRequest request = attributes.getRequest(); //当前服务token
  11. template.header("Authorization","Bearer " + request.getSession().getId()); //template 接收请求方token
  12. }
  13. };
  14. }
  15. }

2.接收方

请求 启动类

  1. @SpringBootApplication
  2. @EnableEurekaClient
  3. public class HelloServiceApplication {
  4. public static void main(String[] args) {
  5. new SpringApplicationBuilder(HelloServiceApplication.class).web(true).run(args);
  6. }
  7. }

 请求Controller

  1. @Controller
  2. @RequestMapping("/hello")
  3. public class HelloController {
  4. @RequestMapping(value="/hello",method = RequestMethod.GET)
  5. @ResponseBody
  6. public List<Map> hello(@RequestParam Map<String, String> queryParam) {
  7. return null;
  8. }
  9. }

猜您喜欢:

  1. Spring boot 内部服务调用 (FeignClient)
  2. Spring Boot系列 – 6. spring boot 实现Restful API
  3. 【Spring Boot】Spring Boot之整合RabbitMQ并实现消息的发送和接收
  4. Spring boot + Spring Security 多种登录认证方式配置(二)
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 猜您喜欢:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档