SpringCloud 服务之间的调用以及负载均衡

RestTemplate服务间调用详解
本文详细介绍了如何使用Spring的RestTemplate进行服务间的远程调用,包括GET、POST、PUT和DELETE请求的使用方法,以及如何通过负载均衡实现请求的高效处理。

RestTemplate

服务间的调用就是在子模块间的相互调用;
在这里插入图片描述
在auth 模块中 调用demo中的有关方法;

在demo中创建一个接口
在这里插入图片描述

在auth中,创建一个RestTemplate 对象,调用
getForObject(“http://服务名/路径”,返回的类型,传递参数的类或map)

  @GetMapping("/yuancheng")
    public String yuancheng(){
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject("http://demo/clientMsg",String.class);
        return response;
    }

然后访问 /yuancheng
调用成功 ,返回 “111”

除了getForObject 还有postForObject 用法相同
put 与 delete 请求的方式,没有返回的参数
例如:
restTemplate.put(“http://HELLO-SERVICE/getbook3”, book, 99);
restTemplate.delete(“http://HELLO-SERVICE/getbook4”, 100);

get请求传参
需要加入占位符,传map

 Map<String,String> map = new HashMap<String,String>();
        map.put("str","hello");
        String response = restTemplate.getForObject("http://demo/clientMsg/?str={str}",String.class,map);
        return response;

接收参数

@GetMapping("/clientMsg")
    public String clientMsg(@RequestParam Map<String,String> map){
        return "222:"+map.get("str");
    }

post传参

 Map<String,String> map = new HashMap<String,String>();
        map.put("str","hello");
        String response = restTemplate.postForObject("http://demo/postTest",map,String.class);
        return response;

 @PostMapping("/postTest")
    public String postTest(@RequestBody Map<String,String> map){
        return "111:"+map.get("str");
    }

负载均衡

在auth中新建一个配置类
在这里插入图片描述
使用@LoadBalanced 注解 ,表示开启客户端负载均衡。

@Configuration
public class RestConfig {
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}


@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/yuancheng")
    public String yuancheng(){
//        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject("http://demo/clientMsg",String.class);
        return response;
    }

}

复制相同的demo子模块,更改不同的端口启动;
同样访问接口

第一次访问
在这里插入图片描述
第二次访问
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值