05-Feign负载均衡

Feign负载均衡

feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service。SpringCloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端,

只需要创建一个接口,然后添加注解即可!

1.微服务名字【ribbon]

2.接口和注解【feign ]

feign 能干什么

在Feign的实现下,我们只需要创建一个接口并使用注解的方式来配置它(类似于以前Dao接口上标注Mapper注解,现在是一个微服务接口上面标注一个Feign注解即可。)

包结构

在这里插入图片描述

第一步、写service

  • springcloud-api
@Component
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {

    @GetMapping("/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id);

    @GetMapping("/dept/list")
    public List<Dept> queryALL();

    @GetMapping("/dept/add")
    public boolean addDept(Dept dept);


}

第二步copy项目 名字为springcloud-sonsumer-dept-feign,添加依赖

  • springcloud-api和本项目都添加feign依赖
   <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-ribbon</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>

第三步、controller层的变化

@RestController
public class DeptConsumerController {
    @Autowired
    private DeptClientService service=null;

    @RequestMapping("/consumer/dept/add")
    public boolean add(Dept dept){
        return  this.service.addDept(dept);
    }

    @RequestMapping("/consumer/dept/get/{id}")
    public Dept get(@PathVariable("id") Long id){
        return  this.service.queryById(id);
    }
    @RequestMapping("/consumer/dept/list")
    public List<Dept> list(){
        return  this.service.queryALL();
    }
}

80-feign controller对比

在这里插入图片描述

第四步、主启动类

@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages = {"com.tian.springcloud"})
//@ComponentScan("com.tian")
public class FeignDeptConsumer_80 {
    public static void main(String[] args) {
        SpringApplication.run(FeignDeptConsumer_80.class,args);
    }
}

开启7001 8001 8002 feign

测试访问 http://localhost/consumer/dept/list

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值