SpringCloud-应用间通信
RestTemplate
纯RestTemplate
public String getMsg() {
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:8788/hello", String.class);
return response;
}
RestTemplate+LoadBalancerClient
@Autowired
private LoadBalancerClient loadBalancerClient;
public String getMsg() {
ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT");
String url = String.format("%s%s", serviceInstance.getUri(), "/hello");
String response = new RestTemplate().getForObject(url, String.class);
return response;
}
- 其实质为Ribbon(与下面实质一样)
- 1.服务发现。依据服务名字将该服务下的所有实例都找出来(Eureka对Ribbon服务实例的维护实现)
- 2.服务监听。检测失效的服务,做到高效剔除。
- 3.服务选择规则。依据规则策略,找到有效的服务。

轮询
服务实例
更改服务选择规则
# bootstrap.properties文件
# PRODUCT为服务名称,比如更改为随机
PRODUCT.ribbon.NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
- 其他的选择规则
![]()
RestTemplate+@LoadBalanced
@Component
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Autowired
private RestTemplate restTemplate;
public String getMsg() {
String response = restTemplate.getForObject("http://PRODUCT/hello", String.class);
return response;
}
OpenFeign
实现背景
调用方(order服务),被调用方(product服务)
order服务中添加product的client模块,并install在本地的meavn仓库中
1.添加依赖(调用方)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.启动类添加注解(调用方)
@EnableFeignClients(basePackages="cloud.product.client")
3.暴露调用接口(被调用方)
<!-- 目的是ProductClient中要使用@FeignClient注解 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign-core</artifactId>
</dependency>
- 用来暴露接口
package cloud.product.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;
// PRODUCT为EUREKA服务中心的注册名,即spring.application.name的值
@FeignClient(
name = "PRODUCT"
)
public interface ProductClient {
@GetMapping({"/hello"}) // 这个要与真正调用的接口完全一致(请求方式+映射路径),
String sayHi();//这个方法名可随意
}
这个是我们真正要调用的服务方的接口
与ProductClient 同处一个服务,但不同模块
package cloud.product.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ServerController {
@RequestMapping("/hello")
public String hello(){
return "hello `";
}
}
4.使用(调用方)
@Autowired(required = false)
private ProductClient productClient;
@GetMapping("/getprdctmsg")
public String getMsg() {
String response = productClient.sayHi();
return response;
}
完整代码详见
- https://github.com/zhaimiya/cloudlearn
菜鸟一枚,学习ing,如有不对之处,烦请大神指点
❀❀ (ง •_•)ง little little 🦆🦆 ❀❀❀❀ ♕♕♕♕♕




浙公网安备 33010602011771号