Spring boot 内部服务调用 (FeignClient)

2021-11-25 09:47:55 浏览数 (1)

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 多种登录认证方式配置(二)

0 人点赞