一、特点
在微服务架构中,业务都会被拆分成一个独立的服务,服务与服务的通讯是基于http restful的。Spring cloud有两种服务调用方式:
1. ribbon+restTemplate
ribbon是一个客户端可以负载均衡的调用方式。
2. fegin
a.fegin集成了ribbon,具有负载均衡的能力;
b.整合了Hystrix,具有熔断的能力;
c.fegin是给予接口注解方式的,使用十分便捷
二、应用
2.1第一种方式:ribbon+restTemplate
2.1.1 在配置文件(.yml)中添加配置文件,注册该工程到服务注册中兴Eureka中,并在启动类中添加配置
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: port: 8764 spring: application: name: service-ribbon
@SpringBootApplication @EnableDiscoveryClient(暴露客户端) public class ServiceRibbonApplication { public static void main(String[] args) { SpringApplication.run(ServiceRibbonApplication.class, args); } @Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); } }
2.1.2 容器中注入:restTemplate
@Bean @LoadBalanced RestTemplate restTemplate() { return new RestTemplate(); }
2.1.3 使用restTemplate调用远程服务
@Service public class HelloService { @Autowired RestTemplate restTemplate; public String hiService(String name) {
//SERVICE-HI是已经注册到服务注册中心的一个微服务
return restTemplate.getForObject("http://SERVICE-HI/hi?name="+name,String.class); }
}
2.2 第二种方式:feign
2.2.1 在配置文件(.yml)中添加配置文件,注册该工程到服务注册中兴Eureka中,并在启动类中添加配置
eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ server: port: 8765 spring: application: name: service-feign
@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients(使用fegin注解) public class ServiceFeignApplication { public static void main(String[] args) { SpringApplication.run(ServiceFeignApplication.class, args); } }
2.2.2通过注解调用()
@FeignClient(value = "service-hi") public interface SchedualServiceHi {
//相当于调用"http://SERVICE-HI/hi?name="+name
@RequestMapping(value = "/hi",method = RequestMethod.GET)
String sayHiFromClientOne(@RequestParam(value = "name") String name);
}