SpringCloud應用間通訊
阿新 • • 發佈:2019-02-12
應用間通訊
HTTP:Spring Cloud
RPC:Dubbo
Spring Cloud中服務間兩種restful呼叫方式:
1,RestTemplate
2,Fegin
RestTemplate的三種使用方式
1.第一種方式(直接使用restTemplate,url寫死)
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://localhost:8080/msg", String.class);
2.第二種方式(利用loadBalancerClient通過應用名獲取url,然後使用restTemplate)
@Autowired private LoadBalancerClient loadBalancerClient; ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCT"); String url = String.format("http://%s:%s", serviceInstance.getHost(), serviceInstance.getPort() + "/msg"); RestTemplate restTemplate = new RestTemplate(); String response = restTemplate.getForObject(url, String.class);
3.第三種方式(需要將restTemplate作為一個bean,利用LoadBalanced,可在restTemplate裡使用應用名字)
@Component
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Autowired private RestTemplate restTemplate; String response = restTemplate.getForObject("http://PRODUCT/msg", String.class);
RestTemplate預設負載均衡策略為輪詢,
自定義負載均衡策略配置(修改為隨機):
PRODUCT:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
客戶端負載均衡器:Ribbon
RestTemplate,Feign,Zuul
服務發現
服務選擇規則
服務監聽
ServerList(通過ServerList獲取所有的可用服務列表),ServerListFilter(根據ServerListFilter過濾掉一部分服務),IRule(通過IRule選擇一個例項作為最終目標結果)
Feign的使用
宣告式REST客戶端(偽RPC)
採用了基於介面的註解
1.引入依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.在啟動類上加註解@EnableFeignClients
3.定義好需要呼叫的介面
@FeignClient(name = "product")
public interface ProductClient {
@PostMapping("/product/listForOrder")
List<ProductInfoOutput> listForOrder(@RequestBody List<String> productIdList);
@PostMapping("/product/decreaseStock")
void decreaseStock(@RequestBody List<DecreaseStockInput> decreaseStockInputList);
}
4.呼叫
@Autowired
private ProductClient productClient;
//查詢商品資訊(呼叫商品服務)
List<ProductInfoOutput> productInfoList = productClient.listForOrder(productIdList);
訊息佇列
訊息中介軟體的選擇
RabbitMQ,Kafka,ActiveMQ
RabbitMQ
安裝
1.進入RabbitMQ下載頁面
2.使用Docker映象
docker run -d --hostname my-rabbit -p 5672:5672 -p 15672:15672 rabbitmq:3.7.3-management
預設帳號:guest,密碼:guest
微服務和容器
從系統環境開始,自底至上打包應用
輕量級,對資源的有效隔離和管理
可複用,版本化