在使用restTemplate访问远程接口的时候,我们难以将接口管理起来,当接口变动的时候我们可能会修改多处。Spring Cloud 提供OpenFeign来解决这个问题。本文将通过配置OpenFeign来访问远程服务。OpenFeign是一种声明式、模板化的HTTP客户端。在Spring Cloud中使用OpenFeign,可以做到使用HTTP请求访问远程服务,就像调用本地方法一样的,开发者完全感知不到这是在调用远程方法,更感知不到在访问HTTP请求。
二、OpenFeign的使用
1.引入库
org.springframework.cloud spring-cloud-starter-openfeign
2.application配置文件内容
server: port: 82 eureka: 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: false eviction-interval-timer-in-ms: 2000 # 连接超时时间设置为3s ribbon: ReadTimeout: 6000 ConnectionTimeout: 6000 #注册服务中心得名字 spring: application: name: cloud-eureka-openfeign datasource: type: com.alibaba.druid.pool.DruidDataSource driver-class-name: org.gjt.mm.mysql.Driver url: jdbc:mysql://101.34.49.127:3306/cloud?useUnicode=true&characterEncoding=utf-8&useSSL=false username: 数据库用户名 password: 数据库密码 mybatis: mapper-locations: classpath:mapper @GetMapping("findPaymentById/{id}") public CommonResult5.service层代码findPaymentById(@PathVariable("id") Long id){ CommonResult commonResult = new CommonResult<>(); try{ commonResult = payment82Service.findPaymentById(id); }catch (Exception e){ e.printStackTrace(); } return commonResult; } }
@Component @FeignClient(value = "CLOUD-EUREKA-CLIENT",path = "paymentController") public interface Payment82Service { @GetMapping(value = "findPaymentById/{id}") CommonResultfindPaymentById(@PathVariable("id") Long id); }
- @FeignClient注解说明连接服务的名称,服务名称为CLOUD-EUREKA-CLIENT
- path代表统一前缀,即提供服务的路径为paymentController/findPaymentById/id
- 若无CommonResult类可用实体类,或String
如图调用82端口返回数据,此数据其实是 CLOUD-EUREKA-CLIENT服务提供的
项目地址: https://gitee.com/xyz1041221997/springcloud.git
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)