SpringCloud服务相互调用RestTemplate

Springcloud中的服务消费,就需要我们服务之前相互发请求了。之前我们都是想着用http请求相关的交互,用的比较多的是

apache httpcomponents ,现在springboot提供了RestTemplate更高级别的方法来满足我们的功能。

RestTemplate 的类路径

 org.springframework.web.client.RestTemplate

其实我们之前就已经集成过了,在spring-boot-starter-web中已经有了它的依赖。

Maven


    org.springframework.boot
    spring-boot-starter-web

基于上一章节,我们重复建1个Biz-2服务,服务名称也要不同

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";
        Map uriVariables = new HashMap<>();
        return restTemplate.getForObject(url,Object.class);
    }
}

Biz-2调用的前提是,注册中心启动了,Biz服务也启动了,这样就OK了。

你可能感兴趣的:(SpringBoot微服务架构)