一、本示例在前文的基础上以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)
方法时,已经作了负载均衡,访问了不一样的端口的服务实例。接口