springCloud 学习笔记3 feign 实现客户端负载均衡

Feign 概述

Feign是Netflix开发的声明式、模板化的HTTP客户端, Feign可以帮助我们更快捷、优雅地调用HTTP API。
Spring Cloud Feign帮助我们定义和实现依赖服务接口的定义。在Spring Cloud feign的实现下,只需要创建一个接口并用注解方式配置它,即可完成服务提供方的接口绑定,简化了在使用Spring Cloud Ribbon时自行封装服务调用客户端的开发量

Feign的使用步骤

1:导入依赖
2:编辑接口
3:在启动类上增加注解
4:项目属性配置
5:业务代码,服务消费者调用服务提供者的服务

导入依赖

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

feign 的应用接口编辑

//polices 从注册中心中获取服务
@FeignClient(name = "polices")
public interface UserFeignClient {
    @RequestMapping(value = "/call/{id}", method = RequestMethod.GET)
    public String call (@PathVariable("id") Long id);
}

启动类上的注解

@SpringBootApplication
@EnableEurekaClient//eurea客户端注解
@EnableFeignClients//fegin客户端注解
public class FirstFeignApplication {
    public static void main(String[] args) {
        SpringApplication.run(FirstFeignApplication.class, args);
    }

}

配置文件application.yml编写

server:
  port: 7000
spring:
  application:
    name: first_feign
eureka:
  client:
    eureka-server-url:
      defautZone: http://localhost:8761/eureka/

业务代码,服务消费者调用服务提供者的服务

@Controller
public class myController {
    //注入Feign接口
    @Autowired
    private UserFeignClient userFeignClient;
    @GetMapping("/router/{id}")
    @ResponseBody
    public String router(@PathVariable("id") Long id ) {
        System.out.println("rout...");
        //   RestTemplate tpl = getRestTemplate();
     //   String json = tpl.getForObject("http://polices/call/1", String.class);
        return userFeignClient.call(id);
    }


    public UserFeignClient getUserFeignClient() {
        return userFeignClient;
    }

    public void setUserFeignClient(UserFeignClient userFeignClient) {
        this.userFeignClient = userFeignClient;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值