前面講了服務的註冊與發現,微服務項目會把項目的各個業務需求劃分紅幾個模塊來單獨提供服務,各服務間的調用都是採用Http Restful來實現,可是在SpringClound中服務間的調用有兩種方式:一種是ribbon+ restTemplate;另外一種是feign;html
Ribbon:在SpringClound中是做爲一個負載均衡的客戶端,控制訪問入口,定製訪問策略等功能; Feign組件同時也是集成了ribbon的java
在Idea裏,新建項目,選擇Spring initializer.web
勾選組件spring
下面的pom瀏覽器
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> <version>1.4.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-ribbon</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
配置properties文件參數;服務器
#服務端口 server.port=8885 #註冊服務中心地址 eureka.client.service-url.defaultZone=http://localhost:8882/eureka/ #註冊服務端name spring.application.name=service-ribbon #調用鏈接時間 eureka.client.eureka-server-read-timeout-seconds=6000 #調用鏈接時間 eureka.client.eureka-server-connect-timeout-seconds=6000 hystrix.metrics.polling-interval-ms=6000
在啓動類上添加註解@EnableDiscoveryClient併發
@EnableDiscoveryClient @SpringBootApplication public class SpringCloundRibbonExampleApplication { public static void main(String[] args) { SpringApplication.run(SpringCloundRibbonExampleApplication.class, args); } /** * ioc注入一個bean: restTemplate;並經過@LoadBalanced註解代表這個restRemplate開啓負載均衡的功能 * * @return */ @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } }
建立conroller、serviceapp
@RestController public class HelloController { @Autowired IHelloService helloService; @RequestMapping(value = "/index") public String index() { return helloService.index(); } }
@Service public class HelloServiceImpl implements IHelloService { @Autowired RestTemplate restTemplate; @Override public String index() { return restTemplate.getForObject("http://SERVICE-HELLO/index",String.class); } }
啓動項目,而後再看服務中心,已經註冊成功負載均衡
回到瀏覽器,輸入http://localhost:8885/indexdom
刷新:
Ribbon自己提供了下面幾種負載均衡策略:
@Configuration
public class RibbonConfiguration {
@Bean
public IRule ribbonRule() {
return new RandomRule();
}
}
咱們能夠經過繼承ClientConfigEnabledRoundRobinRule,來實現本身負載均衡策略。