Springcloud中的服务消费,就需要我们服务之前相互发请求了。之前我们都是想着用http请求相关的交互,用的比较多的是apache httpcomponents ,现在springboot提供了RestTemplate更高级别的方法来满足我们的功能。
需要JAVA Spring Cloud大型企业分布式微服务云构建的B2B2C电子商务平台源码 一零三八七七四六二六 RestTemplate 的类路径
org.springframework.web.client.RestTemplate复制代码
其实我们之前就已经集成过了,在spring-boot-starter-web中已经有了它的依赖。
Maven复制代码 org.springframework.boot spring-boot-starter-web
Biz服务
@RestController@RequestMapping("index")public class IndexController { @Resource private UserService userService; @RequestMapping("findUserMenuList") public Object findUserMenuList(){ return userService.findUserMenuList("李文涛"); }}复制代码
Biz-2服务具体调用如下
@RestController@RequestMapping("index")public class IndexController { @Autowired private RestTemplate restTemplate; String host = "http://SERVICE-BIZ"; //biz服务的名称,大小写忽略 @RequestMapping("index") public Object index(){ String url = host+"/index/findUserMenuList"; MapuriVariables = new HashMap<>(); return restTemplate.getForObject(url,Object.class); }}复制代码
Biz-2调用的前提是,注册中心启动了,Biz服务也启动了,这样就OK了。