运维开发网

Springboot内部服务调用模式

运维开发网 https://www.qedev.com 2022-10-15 14:26 出处:网络
这篇文章主要介绍了Springboot?内部服务调用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

这篇文章主要介绍了Springboot?内部服务调用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教


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


1.请求方

类开始添加评论并扫描Eureka中的所有服务。

@SpringBootApplication@EnableEurekaClient@EnableFeignClientspublic class LoginServiceApplication { public static void main(String[] args) { new SpringApplicationBuilder(LoginServiceApplication.class).web(true).run(args); } }

将包添加到pom.xml中(版本号根据实际情况选择)

lt;dependencygt; lt;groupIdgt;org.springframework.cloudlt;/groupIdgt; lt;artifactIdgt;spring-cloud-starter-feignlt;/artifactIdgt; lt;versiongt;1.4.6.RELEASElt;/versiongt;lt;/dependencygt;

创建接口类

@FeignClient(name="hello-service") //spring service namepublic interface FeignVehicle { @RequestMapping(value="/hello", method = RequestMethod.GET) @ResponseBody public Listlt;Mapgt; hello(@RequestParam Maplt;String,Stringgt; params);}

类实现注入这个接口类。

@AutowiredFeignVehicle feignVehicle;

使用的时候,按照正常的调用方法就可以了。

Maplt;String,Stringgt; map = new HashMaplt;String, Stringgt;();feignVehicle.hello(map);

跨服务调用时,无法获取令牌信息,给发送方增加一个拦截器。

@Configurationpublic class FeignConfiguration { @Bean public RequestInterceptor requestInterceptor() { return new RequestInterceptor() { @Override public void apply(RequestTemplate template) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); //当前服务token template.header("Authorization","Bearer " + request.getSession().getId()); //template 接收请求方token } }; }}


2.接收方

启动请求类

@SpringBootApplication@EnableEurekaClientpublic class HelloServiceApplication { public static void main(String[] args) { new SpringApplicationBuilder(HelloServiceApplication.class).web(true).run(args); } }

请求控制器

@Controller@RequestMapping("/hello")public class HelloController { @RequestMapping(value="/hello",method = RequestMethod.GET) @ResponseBody public Listlt;Mapgt; hello(@RequestParam Maplt;String, Stringgt; queryParam) { return null; }}


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


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



解决办法

模块化时,应该在order的主类中添加以下圈出的注释,以便启动后可以扫描包。


以上个人经验,希望能给你一个参考

0

精彩评论

暂无评论...
验证码 换一张
取 消