您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
小编给大家分享一下Springboot内部服务调用方式有哪些,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!
启动类添加注解,扫描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
}
};
}
}请求 启动类
@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主类上添加下面圈出来的注解,这样启动后就能扫描这个包。

看完了这篇文章,相信你对“Springboot内部服务调用方式有哪些”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。