SpringCloud学习笔记(4)————Ribbon

  1. ribbon是一个基于http 和tcp客户端的负载均衡器,联合eureka时,重写ribbonServerList,扩展从eureka注册中心获取服务端列表。
  2. 新建module:service-ribbon,修改pom.xml。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <parent>
       <groupId>com.springcloud</groupId>
       <artifactId>eureka</artifactId>
       <version>1.0-SNAPSHOT</version>
   </parent>
   <groupId>com.springcloud</groupId>
   <artifactId>service-ribbon</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <packaging>jar</packaging>
   <name>service-ribbon</name>
   <dependencies>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
       </dependency>
       <dependency>
           <groupId>org.springframework.cloud</groupId>
           <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
       </dependency>
   </dependencies>
</project>
  1. 修改appliction.yml
spring:
  application:
    name: service-ribbon
server:
  port: 8764
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  1. 在启动类中添加@EnableEurekaClient,@EnableDiscoveryClient,并向程序中注入bean:restTemplate,通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。
@EnableEurekaClient
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceRibbonApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServiceRibbonApplication.class, args);
	}

	@Bean
	@LoadBalanced
	RestTemplate restTemplate(){
		return new RestTemplate();
	}

}
  1. 编写一个service来消费创建好的“eureka-client”(参照服务的发现),EUREKA-CLIENT为以前配置的名称,链接可以用程序名代替具体的url
@Service
public class HelloService {
    @Autowired
    RestTemplate restTemplate;

    public String hiService(String name) {
        return restTemplate.getForObject("http://EUREKA-CLIENT/test?name=" + name, String.class);
    }
}
  1. 写一个controller,在controller中用调用HelloService 的方法
@RestController
public class HelloController {
    @Autowired
    HelloService helloService;

    @GetMapping("/hi")
    public String hi(@RequestParam String name) {
        return helloService.hiService(name);
    }
}
  1. 修改eureka-client的配置(如下图),以8762端口启动一次,改端口为8763再次启动,之后会出现两个服务。
    SpringCloud学习笔记(4)————Ribbon
    SpringCloud学习笔记(4)————Ribbon
    SpringCloud学习笔记(4)————Ribbon
  2. 启动service-ribbon,访问接口,端口会在8672与8763轮询,以实现负载均衡。
    SpringCloud学习笔记(4)————Ribbon