Spring Cloud的服务有两种消费者,Ribbon是其中之一,它是一个负载均衡客户端,可以很好的控制http和tcp的一些行为,
Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将Netflix的中间层服务连接在一起。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说, 就是在配置文件中列出Load Balancer(简称LB)后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随即连接等)去连接这些机器。我们也很容易使用Ribbon实现自定义的负载均衡算法。
根据Spring Cloud(二)的项目继续更新.不会的请先看上一篇https://blog.csdn.net/qq_39413186/article/details/88972105
同样创建spring cloud项目.借鉴与上一篇文章的创建.这里不在演示了
这里直接切入主题
pom.xml:
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
<version>1.4.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
application.yml:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8764
spring:
application:
name: service-ribbon
启动类:
@SpringBootApplication
@EnableDiscoveryClient
public class XiaofeizheApplication {
public static void main(String[] args) {
SpringApplication.run(XiaofeizheApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate()
{
return new RestTemplate();
}
}
Controller:
@RestController
public class HelloControler {
@Autowired
HelloService helloService;
@RequestMapping(value = "/hi")
public String hi(@RequestParam String name)
{
return helloService.hiService(name);
}
}
service:
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
public String hiService(String name){
return restTemplate.getForObject("http://SERVICE-CLIENT/hi?name=" + name, String.class);//这里就是注册服务名
}
}
启动项目
打开刚才的注册中心
注册成功.做个测试http://localhost:8764/hi?name=cloud
成功的调用了server-client