Ribbon是一個負(fù)載均衡器办悟,它可以讓你對HTTP和TCP客戶機(jī)的行為有很多的控制權(quán)。Feign已經(jīng)使用了Ribbon,所以也可以使用@FeignClient 注解诫龙。先來看一下Ribbon落午。
1.建路由選擇Ribbon
2.pom文件加入配置
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3.配置yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8888/eureka/
server:
port: 9999
spring:
application:
name: service-ribbon
4.修改啟動application中加上
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceribbonApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceribbonApplication.class, args);
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
}
加入HelloControler類
@RestController
public class HelloControler {
@Autowired
HelloService helloService;
@RequestMapping(value = "/hi")
public String hi(@RequestParam String name) {
return helloService.hiService(name);
}
}
加入HelloService
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate;
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-YUAN/hi?name="+name,String.class);
}
}
5.啟動工程谎懦,再次訪問 http://localhost:8888/ 可以看到心加入的SERVICE-RIBBON
6.訪問ribbon,可以看到2個服務(wù)輪詢
7.可以看到2個應(yīng)用程序和一個Ribbon程序都在Rureka注冊了溃斋,當(dāng)我們對SERVICE-RIBBON發(fā)出的請求時會輪詢2個應(yīng)用界拦,起到附在均衡的作用。這兩個應(yīng)用程序都在一臺主機(jī)啟動梗劫,通過配置文件配置不同的端口享甸。Docker的service也有附在均衡的功能截碴,后續(xù)研究如何結(jié)合Docker。