服务消费方Feign & RestTemplate

在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架构





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值