Spring cloud分佈式系統搭建(四)

四、負載均衡的引入

爲了使服務器資源得到充分利用,每次在請求商品服務器時,需要請求不同的服務器,從而達到分擔服務器壓力的效果,其實就是這節要說的負載均衡。又需要“開刀”了!

首先對啓動類下手,給它加上負載均衡的註解:在這裏插入圖片描述

接着改造一下GoodService:

package com.mujio.orderserver.service;


import com.mujio.orderserver.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class GoodService {

    //利用RestTemplate請求接口
    @Autowired
    private RestTemplate restTemplate;

//    @Autowired
//    private DiscoveryClient discoveryClient;

    public Goods getGoods(int id) {
        String serverName = "goods-server";
        String url = "http://" + serverName + "/goods/" + id;
        return restTemplate.getForObject(url,Goods.class);
    }

  /*  public Goods getGoods(int id) {
        String service = "goods-server";
        List<ServiceInstance> instances = discoveryClient.getInstances(service);
        if (instances.isEmpty()) {
            return null;
        }
        //instances.get(0)使用獲取到的第一個服務
        String url = "http://" + instances.get(0).getHost() + ":" + instances.get(0).getPort() + "/goods/" + id;
        return restTemplate.getForObject(url, Goods.class);
    }*/

/*    public Goods getGoods(int id){
        String url = "http://localhost:8000/goods/" + id;
        Goods goods = new Goods();
        goods.setId(0);
        goods.setName("未能獲取到商品信息");
        goods.setPrice("");
        Goods g;
        try {
            g = restTemplate.getForObject(url, Goods.class);
        } finally {
                g = goods;
            return g;
        }

    }*/
}

現在請求的時候只需要代入服務名稱,eureka就會自動去識別,至於請求具體哪一個商品服務,則是由@LoadBalanced引入的負載均衡來控制了。

爲了測試負載均衡的效果,可以讓商品服務的controller在接收到請求時打印一下標識,讓三個controller分別打印goods-server、goods-server01和goods-server02:在這裏插入圖片描述

重新啓動,訪問http://localhost:9001/order/5,仔細觀察對應的輸出結果,可以發現每次訪問的商品服務並不是固定的,負載均衡爲我們實現了輪詢功能,但是具體按什麼順序去查詢的呢?自己去探究去吧,我沒探究,哈哈哈哈哈哈哈……

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章