服务消费方Feign & RestTemplate
2018年01月04日 15:59:22 llianlianpay 阅读数:3765
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/llianlianpay/article/details/78971910
在Spring cloud有两种服务调用方式,一种是ribbon+restTemplate,另一种是feign,鉴于feign注解化更方便使用,先讲解feign.
demo中使用的注册中心是eureka,如果使用consul,需要修改配置:
-
#spring:
-
# profiles:
-
# active: dev
-
# application:
-
# name: service-feign
-
###################### consul ###########################
-
# cloud:
-
# consul:
-
# host: 192.168.1.102
-
# port: 8500
-
# discovery:
-
# healthCheckUrl: http://localhost:${server.port}/health
-
# healthCheckInterval: 15s
-
# instance-id: service-feign
-
# enabled: true
-
# heartbeat:
-
# enabled: true
-
/**
-
* @这个Client由服务提供方提供,如euraka-server-provider里面的client包提供
-
* @添加@FeignClient注解是为了调用方的在服务注册机器上找到服务提供方
-
*/
-
@FeignClient(value = "service-provider") //这里的name对应调用服务的spring.applicatoin.name
-
public interface ServiceFeignClient {
-
@RequestMapping(value = "/hi")
-
String hi(@RequestParam("id") String id);
-
}
使用注解 @EnableFeignClients启动feign
https://github.com/nick8sky/spring-clouds/eureka-consumer-feign
restTemplate:
ribbon是一个负载均衡客户端,可以很好的控制htt和tcp的一些行为。Feign默认集成了ribbon。
注意:ribbon未实现实效转移。
在它的pom.xml文件分别引入起步依赖spring-cloud-starter-eureka、spring-cloud-starter-ribbon、spring-boot-starter-web
在工程的启动类中,通过@EnableDiscoveryClient向服务中心注册;并且向程序的ioc注入一个bean: restTemplate;并通过@LoadBalanced注解表明这个restRemplate开启负载均衡的功能。
-
@SpringBootApplication
-
@EnableDiscoveryClient
-
public class ClientApplication {
-
public static void main(String[] args) {
-
SpringApplication.run(ClientApplication.class, args);
-
}
-
@Bean
-
@LoadBalanced
-
RestTemplate restTemplate(){
-
return new RestTemplate();
-
}
-
}
在浏览器上多次访问http://localhost:8910/hi?name=nick,浏览器交替显示
-
@RequestMapping("/hi")
-
public String hi(@RequestParam String id){
-
return restTemplate.getForObject("http://service-provider/hi?id="+id, String.class);
-
}
ribbon架构