SpringCloud (四)、Ribbon消費者初體驗-v1.0

一、本示例在前文的基礎上以myclient爲消費者,啓動兩個myserver爲生產者服務web

二、myclient添加依賴spring

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

三、在工程的啓動類中,經過@EnableDiscoveryClient向服務中心註冊;而且向程序的ioc注入一個bean: restTemplate;並經過@LoadBalanced註解代表這個restRemplate開啓負載均衡的功能。app

@EnableEurekaClient //啓動EnableEureka客戶端
@EnableDiscoveryClient
@SpringBootApplication
public class MyClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyClientApplication.class, args);
    }
    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

四、寫一個測試類DemoService,經過以前注入ioc容器的restTemplate來消費MYSERVER服務的「/myserver/demo/hello」接口,在這裏咱們直接用的程序名替代了具體的url地址,在ribbon中它會根據服務名來選擇具體的服務實例,根據服務實例在請求的時候會用具體的url替換掉服務名,代碼以下:負載均衡

package com.myclient.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class DemoService {
    @Autowired
    RestTemplate restTemplate;

    public String hiService(String name) {
        return restTemplate.getForObject("http://MYSERVER/myserver/demo/hello/"+name,String.class);
    }
}

五、寫一個controller,在controller中用調用DemoService 的方法,代碼以下:測試

package com.myclient.demo.controller;

import com.myclient.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/myclient/demo")
public class DemoController {

    @Autowired
    private DemoService demoService;

    @Value("${test}")
    private String test;

    @GetMapping("/test")
    public String getTest()
    {
        return test;
    }

    @GetMapping("/hello/{name}")
    public String hello(@PathVariable String name){
        return demoService.hiService(name);
    }

}

六、COPY一個MYSERVER服務分別修改端口爲8090、8095url

七、啓動兩個MYSERVER實例rest

八、發送一個myclient請求server

這說明當咱們經過調用blog

restTemplate.getForObject("http://MYSERVER/myserver/demo/hello/"+name,String.class)

方法時,已經作了負載均衡,訪問了不一樣的端口的服務實例。接口

相關文章
相關標籤/搜索