上篇文章讲到了eureka服务注册中心的搭建,这篇文章主要讲解如何进行feign调用,以及记录新版本springcloud(2021.0.0版本)中feign依赖的选择以及ribbon问题。 依旧是三步走:
1.导入依赖
2.编写配置文件
3.主启动类加上注解支持
4.业务处理
1. 导入依赖
注意: 新版本使用的是openfeign,同时摒弃掉了ribbon,改用了loadbalancer,所以需要在eureka-client依赖中剔除ribbion,同时加入loadbalancer依赖
整体pom.xml文件
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
2. 编写配置文件
application.yml 对于eureka配置文件:核心就是instance client server 这三大块
spring:
profiles:
active: test
main:
allow-circular-references: true
application:
name: hospital
eureka:
instance:
ip-address: true # 是否以ip形式注册
lease-expiration-duration-in-seconds: 90 # 接受服务心跳间隔时间 超过这个间隔 就移除这个服务
lease-renewal-interval-in-seconds: 30 # 表示 Eureka Client 向 Eureka Server 发送心跳的频率(默认 30 秒)
client:
register-with-eureka: true #是否向服务注册中心注册自己 默认true
fetch-registry: true #是否从eureka拉取注册表信息 默认true
service-url:
defaultZone: http://xxx:9001/eureka # 服务注册中心地址
3.主启动类加上注解支持
@EnableFeignClients
package com.cz;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
//@MapperScan(basePackages = "com.cz.dao.*")
@Slf4j
@EnableFeignClients
public class HospitalApplication {
public static void main(String[] args) {
log.info("程序起飞啦!!!");
SpringApplication.run(HospitalApplication.class, args);
}
}
启动项目,确保服务成功注册到eureka服务注册中心上
4.Feign使用
name属性表示你所要调用的服务的名称。通过配置文件spring.application.name进行配置,这里只是简单的举个例子。在实际开发中,需要自己写对应的业务逻辑,注入feign接口类,调用fegin的方法,就是调用对应微服务的方法 下图就是自己简单写的另外一个springboot项目:hospatial-doctor,并且注册到eureka上。这样就可以通过服务名称来调用到另外一个服务
package com.cz.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @Date 2022/2/8 18:52
* @Description
* @Param
*/
@FeignClient(name = "hospatial-doctor")
public interface DoctorService {
@RequestMapping(value = "/test",method = RequestMethod.POST)
public String test();
}
推荐文章
发表评论