简介:是一个基于Http、tcp协议的客户端负载均衡工具,当浏览器向后端发送请求时,选取Eureka Server 中的可用服务提供者列表,根据负载均衡策略,选取一个可用服务发送请求
负载均衡策略:轮询(RoundRobin)、随机(Radom)、请求数最少(BestAvailable)
代码示例如下:
注:此示例基于 springboot1.5.10
1、eureka server 此模块内容在此省略
2、服务提供者模块
添加依赖:只需添加必要的依赖,无需添加特定依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>1.4.3.RELEASE</version> </dependency>
application配置:
server: port: 7904 #程序启动端口,也是Tomcat端口 spring: application: name: provider-user #应用别名 eureka: client: service-url: defaultZone: http://user:123@localhost:10000/eureka instance: instance-id: ${spring.cloud.client.ipAddress}:${spring.application.name}:${spring.application.instance_id:${server.port}} prefer-ip-address: true #是否以ip显示host
启动类:
@SpringBootApplication @EnableEurekaClient //启用eureka客户端 public class providerApplication { public static void main( String[] args ) { SpringApplication.run(providerApplication.class,args); System.out.println("provider-user start-up success"); } }
3、服务消费者模块
添加依赖:与服务提供者相同
application配置
server: port: 8900 #程序启动端口,也是Tomcat端口 spring: application: name: customer-order-ribbon #应用别名 eureka: client: service-url: defaultZone: http://user:123@localhost:10000/eureka instance: instance-id: ${spring.cloud.client.ipAddress}:${spring.application.name}:${spring.application.instance_id:${server.port}} prefer-ip-address: true # eureka.instance.preferIpAddress=true #eureka.instance=instance-id=${spring.cloud.client.ipAddress}:${spring.application.name}:${spring.application.instance_id:${server.port}} #user: # url: http://localhost:7900/user/
配置类
@Configuration public class TestRibbonConfig { @Autowired IClientConfig iClientConfig; @Bean public IRule testRibbon(IClientConfig iClientConfig){ return new RandomRule(); } }
启动类
@SpringBootApplication @EnableEurekaClient @RibbonClient(name="PROVIDER-USER",configuration = TestRibbonConfig.class) //启用ribbon,并对 PROVIDER-USER 进行负载均衡 public class customerApplication { @Bean @LoadBalanced public RestTemplate getTemp(){ return new RestTemplate(); } public static void main( String[] args ) { SpringApplication.run(customerApplication.class,args); System.out.println("customer start-up success"); } }
Controller
@RestController public class CustomeController { @Autowired private EurekaClient eurekaClient; @Autowired private RestTemplate restTemplate;//springboot提供的用于访问rest接口的对象 @Autowired private LoadBalancerClient loadBalancerClient; @GetMapping("/testRibbon") public String testRibbon(){ ServiceInstance choose = loadBalancerClient.choose("PROVIDER-USER"); System.err.println("testRibbon:serviceId"+choose.getServiceId()+",host:"+choose.getHost()+",port:"+choose .getPort()); return "testRibbon:"+choose.getPort(); } }
注:如果需要访问其他微服务模块,可使用rest接口