Springboot 内部服务调用方式
更新时间:2022年03月14日 17:28:10 作者:Kings菜鸟
这篇文章主要介绍了Springboot 内部服务调用方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
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 添加包 (版本号 根据实际选择)
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> <version>1.4.6.RELEASE</version> </dependency>
创建接口类
@FeignClient(name="hello-service") //spring service name
public interface FeignVehicle {
@RequestMapping(value="/hello", method = RequestMethod.GET)
@ResponseBody
public List<Map> hello(@RequestParam Map<String,String> params);
}实现类注入此接口类
@Autowired FeignVehicle feignVehicle;
使用的时候直接按照正常调用方式即可
Map<String,String> map = new HashMap<String, String>(); 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
.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("/hello")
public class HelloController {
@RequestMapping(value="/hello",method = RequestMethod.GET)
@ResponseBody
public List<Map> hello(@RequestParam Map<String, String> queryParam) {
return null;
}
}多模块化,服务间调用的坑
问题背景
product服务作为服务端,提供了一个 对外通信Fegin接口 ProductClient,放在了com.imooc.product.client jar包下order服务作为客户端,直接引用上面的jar,使用 ProductClient ,启动主类后报下图错误:

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

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Liquibase结合SpringBoot使用实现数据库管理功能
Liquibase 是一个强大的数据库管理工具,它帮助你通过自动化管理数据库的变更、版本控制、和回滚,简化了开发中的数据库迁移工作,这篇文章主要介绍了Liquibase结合SpringBoot使用实现数据库管理,需要的朋友可以参考下2024-12-12
selenium4.0版本在springboot中的使用问题的坑
本文主要介绍了selenium4.0版本在springboot中的使用问题的坑,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-07-07
使用mybatis的typeHandler对clob进行流读写方式
这篇文章主要介绍了使用mybatis的typeHandler对clob进行流读写方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2022-01-01
MyBatis写入Json字段以及Json字段转对象示例详解
这篇文章主要给大家介绍了关于MyBatis写入Json字段以及Json字段转对象的相关资料,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-07-07


最新评论