Springboot 内部服务调用方式

网友投稿 366 2022-08-20


Springboot 内部服务调用方式

目录Eureka注册的服务之间互相调用1.请求方2.接收方多模块化,服务间调用的坑问题背景解决办法

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

1.请求方

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

@SpringBootApplication

@EnableEurekaClient

@EnableFeignClients

public class LoginServiceApplication {

public static void main(String[] args) {

new SpringApplicationBuilder(LoginServiceApplication.class).web(true).run(args);

}

}

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

org.springframework.cloud

spring-cloud-starter-feign

1.4.6.RELEASE

</dependency>

创建接口类

@FeignClient(name="hello-service") //spring service name

public interface FeignVehicle {

@RequestMapping(value="/hello", method = RequestMethod.GET)

@ResponseBody

public List hello(@RequestParam Map params);

}

实现类注入此接口类

@Autowired

FeignVehicle feignVehicle;

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

Map map = new HashMap();

feignVehicle.hello(map);

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

@Configuration

public class FeignConfiguration {

@Bean

public RequestInterceptor requestInterceptor() {

return new RequestInterceptor() {

@Override

public void apply(RequestTemplate template) {

ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder

cRKlSfBUQ .getRequestAttributes();

HttpServletRequest request = attributes.getRequest(); //当前服务token

template.header("Authorization","Bearer " + request.getSession().getId()); //template 接收请求方token

}

};

}

}

2.接收方

请求 启动类

@SpringBootApplication

@EnableEurekaClient

public class HelloServiceApplication {

public static void main(String[] args) {

new SpringApplicationBuilder(HelloServiceApplication.class).web(true).run(args);

}

}

请求Controller

@Controller

@RequestMapping("/hellhttp://o")

public class HelloController {

@RequestMapping(value="/hello",method = RequestMethod.GET)

@ResponseBody

public List hello(@RequestParam Map queryParam) {

return null;

}

}

多模块化,服务间调用的坑

问题背景

product 服务作为服务端,提供了一个 对外通信Fegin接口 ProductClient,放在了com.imooc.product.client jar包下order 服务作为客户端,直接引用上面的jar,使用 ProductClient ,启动主类后报下图错误:

解决办法

多模块化时,应该在order主类上添加下面圈出来的注解,这样启动后就能扫描这个包。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:使用Feign设置Token鉴权调用接口
下一篇:Java 精炼解读类和对象原理
相关文章

 发表评论

暂时没有评论,来抢沙发吧~