当前位置:网站首页>RestTemplate 服务调用

RestTemplate 服务调用

2022-04-23 21:58:00 Leon_Jinhai_Sun

# 1.创建两个服务并注册到consul注册中心中
- users    代表用户服务 端口为 9999
- products 代表商品服务 端口为 9998
    `注意:这里服务仅仅用来测试,没有实际业务意义

 

# 2.在商品服务中提供服务方法

@RestController
@Slf4j
public class ProductController {
    @Value("${server.port}")
    private int port;
    @GetMapping("/product/findAll")
    public Map<String,Object> findAll(){
        log.info("商品服务查询所有调用成功,当前服务端口:[{}]",port);
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("msg","服务调用成功,服务提供端口为: "+port);
        map.put("status",true);
        return map;
    }
}
# 3.在用户服务中使用restTemplate进行调用
@RestController
@Slf4j
public class UserController {
    @GetMapping("/user/findAll")
    public String findAll(){
        log.info("调用用户服务...");
        //1.使用restTemplate调用商品服务
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject("http://localhost:9998/product/findAll", 
                                                     String.class);
        return forObject;
    }
}
# 4.启动服务

# 5.测试服务调用
- 浏览器访问用户服务 http://localhost:9999/user/findAll

 # 6.总结
- rest Template是直接基于服务地址调用没有在服务注册中心获取服务,也没有办法完成服务的负载均衡如果需要实现服务的负载均衡需要自己书写服务负载均衡策略。

版权声明
本文为[Leon_Jinhai_Sun]所创,转载请带上原文链接,感谢
https://blog.csdn.net/leon_jinhai_sun/article/details/124210700