学习博客:【SpringCloud】Feign

Feign与Ribbon的区别在于,Ribbon使用微服务名来访问,利用RestTemplate对Http请求封装处理,而Feign在此基础上进一步封装,使用接口和注解,这会使Http客户端的编写更容易。Feign相较Ribbon可读性提高,但性能降低


项目结构
在这里插入图片描述

导入依赖

        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>3.1.3</version>
        </dependency>

Service接口,开启注解@FeignClient

@FeignClient(value = "http://SPRINGCLOUD-PROVIDER-DEPT")
public interface DeptClientService {

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

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

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


项目结构
在这里插入图片描述
配置文件

server:
  port: 80

spring:
  application:
    name: SPRINGCLOUD-CONSUMER-DEPT

eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
    register-with-eureka: false #不注册到eureka中
  instance:
    instance-id: springcloud-consumer-dept80  #描述信息
    prefer-ip-address: true #优先使用ip注册,访问显示ip

management:
  endpoints:
    web:
      exposure:
        include: "*"
  info:
    env:
      enabled: true

# 暴露端点info
info:
  app.name: yl-springcloud
  company.name: www.yl.com
  build.artifactId: com.yl.springcloud
  build.version: 1.0-SNAPSHOT

Controller

@RestController
public class DeptConsumerController {

    //消费者没有service
    //RestTemplate 直接调用 注册到spring
    //(URL,实体 Map, Class<T>,  responseType)

    @Autowired
    private DeptClientService service = null;

    @GetMapping("/consumer/dept/get/{id}")
    public Dept queryById(@PathVariable("id") Long id){
        return this.service.queryById(id);
    }

    @GetMapping("/consumer/dept/list")
    public List<Dept> queryAll(){
        return this.service.queryAll();
    }

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

}

主启动类,开启注解@EnableFeignClients

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

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值