springCloud学习笔记(五)——OpenFeign服务调⽤映射
一、OpenFeign的作用和含义
在使用restTemplate访问远程接口的时候,我们难以将接口管理起来,当接口变动的时候我们可能会修改多处。Spring Cloud 提供OpenFeign来解决这个问题。本文将通过配置OpenFeign来访问远程服务。OpenFeign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用OpenFeign,可以做到使用HTTP请求访问远程服务,就像调用本地方法一样的,开发者完全感知不到这是在调用远程方法,更感知不到在访问HTTP请求。
二、OpenFeign的使用
1.引入库
<!--openfeign --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId></dependency>
2.application配置文件内容
server:port: 82eureka:instance:hostname: eureka7001.com #eureka服务端的实例名称instance-id: clientOpenFeign82 #服务中心中具体区分的名称prefer-ip-address: true #访问路径可以显示IP地址lease-renewal-interval-in-seconds: 1 #向服务端发送心跳的时间间隔,单位为秒(默认是30秒)lease-expiration-duration-in-seconds: 2 #收到最后一次心跳后等待时间上限,单位为秒(默认是90秒),超时将剔除client:register-with-eureka: true #false表示不向注册中心注册自己fetch-registry: true #false表示自己端就是注册中心service-url:# defaultZone: http://eureka7001.com:7001/eureka/ #单机defaultZone: http://eureka7001.com:7001/eureka/ #集群server:# 关闭自我保护机制,保证不可用服务被及时剔除enable-self-preservation: falseeviction-interval-timer-in-ms: 2000# 连接超时时间设置为3sribbon:ReadTimeout: 6000ConnectionTimeout: 6000#注册服务中心得名字spring:application:name: cloud-eureka-openfeigndatasource:type: com.alibaba.druid.pool.DruidDataSourcedriver-class-name: org.gjt.mm.mysql.Driverurl: jdbc:mysql://101.34.49.127:3306/cloud?useUnicode=true&characterEncoding=utf-8&useSSL=falseusername: 数据库用户名password: 数据库密码mybatis:mapper-locations: classpath:mapper/*.xml
3.main方法声明使用feign组件
@SpringBootApplication//声明使用feign组件@EnableFeignClientspublic class CloudEurekaOpenfeignApplication82 {public static void main(String[] args) {SpringApplication.run(CloudEurekaOpenfeignApplication82.class, args);}}
4.Controller控制层代码
@RestControllerpublic class PaymentController {@ResourcePayment82Service payment82Service;/**** description: 通过id查询Payment数据* version: 1.0 ->* date: 2021/11/17 13:55* author: xiaYZ* iteration: 迭代说明* @param id* @return com.example.comment.entity.CommonResult<com.example.comment.entity.Payment>*/@GetMapping("findPaymentById/{id}")public CommonResult<Payment> findPaymentById(@PathVariable("id") Long id){CommonResult<Payment> commonResult = new CommonResult<>();try{commonResult = payment82Service.findPaymentById(id);}catch (Exception e){e.printStackTrace();}return commonResult;}}
5.service层代码
/*** @description: 连接CLOUD-EUREKA-SERVICE注册服务* @author: xiaYZ* @createDate: 2021/11/17* @version: 1.0*/@Component@FeignClient(value = "CLOUD-EUREKA-CLIENT",path = "paymentController")public interface Payment82Service {/*** description: 通过id查询Payment数据* version: 1.0* date: 2021/11/17 14:38* author: xiaYZ* iteration: 迭代说明* @param id* @return*/@GetMapping(value = "findPaymentById/{id}")CommonResult<Payment> findPaymentById(@PathVariable("id") Long id);}
- @FeignClient注解说明连接服务的名称,服务名称为CLOUD-EUREKA-CLIENT1. path代表统一前缀,即提供服务的路径为paymentController/findPaymentById/id1. 若无CommonResult类可用实体类,或String
6.测试结果

如图调用82端口返回数据,此数据其实是 CLOUD-EUREKA-CLIENT服务提供的
