前面讲了服务的注册与发现,微服务项目会把项目的各个业务需求划分红几个模块来单独提供服务,各服务间的调用都是采用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,来实现本身负载均衡策略。