在springCloud微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的。Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign。在这一篇文章首先讲解下基于ribbon+rest。
1.Ribbon
Ribbon中的中心概念是指定客户端的概念。每个负载平衡器是组合的组合的一部分,负载均衡客户端,可以很好的控制htt和tcp的一些行为.(服务负载均衡器)
Ribbon 已经默认实现了这些配置bean:
IClientConfig ribbonClientConfig: DefaultClientConfigImpl
IRule ribbonRule: ZoneAvoidanceRule
IPing ribbonPing: NoOpPing
ServerList ribbonServerList: ConfigurationBasedServerList
ServerListFilter ribbonServerListFilter: ZonePreferenceServerListFilter
ILoadBalancer ribbonLoadBalancer: ZoneAwareLoadBalan
2.yml 文件如下:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/ //注册中心地址
server:
port: 8764
spring:
application:
name: service-ribbon
3.示例代码
在工程的启动类中,通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。
1.@EnableDiscoveryClient //向服务中心注册 并且向程序的ioc注入一个bean: restTemplate;
2.@LoadBalanced注解 //表明这个restRemplate开启负载均衡的功能。
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
public class ServiceRibbonApplication {
public static void main(String[] args) {
SpringApplication.run( ServiceRibbonApplication.class, args );
}
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate(); //默认提供
}
}
写一个测试类HelloService,通过之前注入ioc容器的restTemplate来消费service-hi服务的“/hi”接口,在这里我们直接用的程序名替代了具体的url地址,在ribbon中它会根据服务名来选择具体的服务实例,根据服务实例在请求的时候会用具体的url替换掉服务名,代码如下:
@Service
public class HelloService {
@Autowired
RestTemplate restTemplate; //注入
public String hiService(String name) {
return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class); //
}
}