springboot2.x引入feign
一、需求
最近公司项目需求,需要调用第三方服务的接口,所以选用了feign来实现(这里只说springboot2.x的pom引用,没有怎么使用,网上一大顿)。
二、什么是feign
feign是声明式的web service客户端,它让微服务之间的调用变得更简单了,类似controller调用service。Spring Cloud集成了Ribbon和Eureka,可在使用Feign时提供负载均衡的http客户端。
三、springboot1.x中feign的使用(这里不展示hystrix熔断的配置和实现)
3.1 在pom.xml中加入依赖
<!-- feign依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
<!-- hystrix 断路器依赖 用于处理请求第三方接口超时 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
3.2 在启动类上添加注解@EnableFeignClients
@EnableCaching
@EnableAutoConfiguration
@SpringBootApplication
@EnableConfigurationProperties
@ServletComponentScan//配置druid必须加的注解,如果不加,访问页面打不开,filter和servlet、listener之类的需要单独进行注册才能使用,spring boot里面提供了该注解起到注册作用
@EnableTransactionManagement
@EnableFeignClients
@EnableHystrix
@EnableCircuitBreaker
@EnableHystrixDashboard
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
3.3 启动springboot的启动类
四、springboot2.x中feign的使用(这里不展示hystrix熔断的配置和实现)
在另外项目中引用的时候用的是spring2.x,所以就出现问题了,引入feign失败。网上说springboot2.x需要如下引入:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
但是我使用openfeign在启动的时候报错:
所以我将pom.xml的依赖改成了这样(<parent>一定要注释掉):
<!-- 此处一定要注释掉parent继承父级的依赖 -->
<!--<parent>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-parent</artifactId>-->
<!--<version>2.1.2.RELEASE</version>-->
<!--</parent>-->
<dependencies>
<!-- ...其他的依赖省略了 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
<version>1.2.3.RELEASE</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId>
<version>2.0.0.RC1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
启动类注解和springboot1.x中的一样,启动工程,就可以了。
此篇只是工作中问题的记录,有理解更深的朋友,欢迎告诉我。