在微服务架构中,业务都会被拆分红一个独立的服务,服务与服务的通信是基于http restful的。Spring cloud有两种服务调用方式:web
一种是ribbon+restTemplate,spring
另外一种是feign。restful
ribbon是一个负载均衡客户端,能够很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。架构
ribbon
核心组件有三个负载均衡
1.服务注册中心tcp
2.服务提供方:多个serviceide
1.pom.xmlspring-boot
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.3.5.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-ribbon</artifactId> </dependency> <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> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Brixton.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
2.@EnableDiscoveryClient
注解来添加发现服务能力微服务
3.经过@LoadBalanced注解代表这个restRemplate开启负载均衡的功能。spa
RestTemplate
构建RestTemplate
对应的bean,在method上使用注解@LoadBalanced表示restTemplate使用LoadBalancerClient
执行请求
@Configuration public class RibbonConfig { /** * LoadBalanced 注解代表restTemplate使用LoadBalancerClient执行请求 */ @Bean @LoadBalanced public RestTemplate restTemplate() { RestTemplate template = new RestTemplate(); SimpleClientHttpRequestFactory factory = (SimpleClientHttpRequestFactory) template.getRequestFactory(); factory.setConnectTimeout(3000); factory.setReadTimeout(3000); return template; } }
4.controller直接注入resttemplate,调用服务,便可
注:若是使用了feign,Feign默认集成了ribbon,无须任何配置,调用服务,请求会自动轮询到每一个服务端来处理。