当前位置:网站首页>Resttemplate service call

Resttemplate service call

2022-04-23 22:10:00 Leon_ Jinhai_ Sun

# 1. Create two services and register to consul In the registry
- users     Service on behalf of users Port is 9999
- products On behalf of goods and services Port is 9998
    ` Be careful : The service here is just for testing , There is no practical business significance

 

# 2. Service method in commodity service 

@RestController
@Slf4j
public class ProductController {
    @Value("${server.port}")
    private int port;
    @GetMapping("/product/findAll")
    public Map<String,Object> findAll(){
        log.info(" Commodity service query all calls succeeded , Current service port :[{}]",port);
        Map<String, Object> map = new HashMap<String,Object>();
        map.put("msg"," Service call succeeded , The service provider port is : "+port);
        map.put("status",true);
        return map;
    }
}
# 3. Use in user services restTemplate To call 
@RestController
@Slf4j
public class UserController {
    @GetMapping("/user/findAll")
    public String findAll(){
        log.info(" Call the user service ...");
        //1. Use restTemplate Call commodity service 
        RestTemplate restTemplate = new RestTemplate();
        String forObject = restTemplate.getForObject("http://localhost:9998/product/findAll", 
                                                     String.class);
        return forObject;
    }
}
# 4. Start the service 

# 5. Test service invocation 
-  Browser access to user services  http://localhost:9999/user/findAll

 # 6. summary
- rest Template It is called directly based on the service address, and the service is not obtained in the service registry , There is no way to achieve service load balancing. If you need to achieve service load balancing, you need to write your own service load balancing strategy .

版权声明
本文为[Leon_ Jinhai_ Sun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/113/202204232157394049.html