一、建一个服务消费者
新建一个项目,命名为hello-service-ribbon
pom.xml依赖如下:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
二、配置application.properties
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ spring.application.name=hello-service-ribbon server.port=8083
在工程的启动类中,通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。
@SpringBootApplication @EnableDiscoveryClient public class HelloServiceRibbonApplication { public static void main(String[] args) { SpringApplication.run(HelloServiceRibbonApplication.class, args); } @Bean @LoadBalanced public RestTemplate restTemplate(){ return new RestTemplate(); } }
编写测试类HelloService,代码如下:
@Service public class HelloService { @Autowired RestTemplate restTemplate; public String helloService(String name){ return restTemplate.getForObject("http://HELLO-SERVICE/hi?name="+name,String.class); } }
再编写一个controller,如下:
@RestController public class HelloController { @Autowired HelloService helloService; @RequestMapping(value="/hi") public String hello(@RequestParam String name){ return helloService.helloService(name); } }
hello-service中的代码如下:
@SpringBootApplication @EnableDiscoveryClient @RestController public class HelloServiceApplication { public static void main(String[] args) { SpringApplication.run(HelloServiceApplication.class, args); } @Value("${server.port}") String port; @RequestMapping("/hi") public String home(@RequestParam String name) { return "hi "+name+",i am from port:" +port; } }
在浏览器上多次访问http://localhost:8083/hi?name=zhao,浏览器交替显示:
hi zhao,i am from port:8081
hi zhao,i am from port:8082