在集群环境下,负载均衡很重要。下面演示客户端的负载均衡ribbon
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
eureka client的依赖中已经集成了ribbon的依赖,所以不用引依赖了。
创建第一个服务端:
controller代码:
package com.xhx.springcloud.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* xuhaixing
* 2018/6/3 16:18
*/
@RestController
@RequestMapping(value = "hello")
public class HelloController {
@RequestMapping(value = "getName")
public String getName(String name){
return name+2;
}
}
配置文件
server:
port: 8081
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: eureka-service
创建第二个服务端,spring.spplication.name应该和第一个服务端一样
package com.xhx.springcloud.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* xuhaixing
* 2018/6/3 16:18
*/
@RestController
@RequestMapping(value = "hello")
public class HelloController {
@RequestMapping(value = "getName")
public String getName(String name){
return name+1;
}
}
配置文件:
server:
port: 8080
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: eureka-service
启动eureka与两个服务端,然后打开网页127.0.0.1:8761
可以看到两个服务端都注册到一起了。
创建一个eureka-client
配置ribbon
package com.xhx.springcloud.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* xuhaixing
* 2018/6/3 16:24
*/
@Configuration
public class RibbonConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
配置文件:
server:
port: 8085
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
spring:
application:
name: eureka-client
controller,注入restTemplate,通过服务名称请求eureka-server
package com.xhx.springcloud.controller;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* xuhaixing
* 2018/6/3 16:27
*/
@RestController
public class RibbionController {
@Autowired
private RestTemplate restTemplate;
@RequestMapping(value = "getName")
public String getName(String name){
return restTemplate.getForObject("http://eureka-service/hello/getName?name="+name,String.class);
}
}
用postman请求,一次返回 xxx1 一次返回xxx2,采用的轮询策略
实时内容请关注微信公众号,公众号与博客同时更新:程序员星星