前言
接触springboot有三四年的时间,调用接口一直用restTemplate. postForObject等这样方法,也知道有feign这样的调用方法,但一直没有实践过,今天抽空试了一下,没有应用到开发中,但目前感觉还是比较方便的。
筹备
需要三个项目:
1、feign-client 客户端
2、feign-consumer 消费端
3、eureka-server 不再多说
开始1、
新建springboot项目,命名为feign-client,引入feign和eureka
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
main文件顺代开启两个配置
@SpringBootApplication
@EnableFeignClients //启用feign客户端
@EnableEurekaClient //启用eureka客户端
public class FeignClientApplication {
public static void main(String[] args) {
SpringApplication.run(FeignClientApplication.class, args);
}
}
配置文件如下
server.port=9002
spring.application.name=feign-client
eureka.client.service-url.defaultZone=http://localhost:9000/eureka/
新建Hello测试文件,最最原生,没有多余的代码
package com.zsh.api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloApi {
@RequestMapping("/hello")
public String sayHello() {
return "hello feign";
}
}
开始2 ,
新建springboot的feign-consumer项目,同样引用和开启feign和eureka
和feign-client项目相同,这里不再累赘
新建feignClient引用文件
package com.zsh.FeignClient;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient("feign-client")
//注意,这里的feign-client 是feign-client项目的spring.application.name 不要写错
public interface HelloFeignClient{
@GetMapping("/hello")
public String sayHello();
}
新建测试文件
package com.zsh.api;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloApi {
@RequestMapping("/hello")
public String sayHello() {
return "hello feign";
}
}
至此全部完成
@auth 填过坑1
HelloFeignClient 一开始没有加注解@FeignClient("feign-client")
一直在提示
***************************
APPLICATION FAILED TO START
***************************
Description:
Field helloFeignClient in com.zsh.controller.HelloController required a bean of type 'com.zsh.FeignClient.HelloFeignClient' that could not be found.
Action:
Consider defining a bean of type 'com.zsh.FeignClient.HelloFeignClient' in your configuration.
@auth 填过坑1
public String sayHello();
没有加注解 @GetMapping("/hello")
提示
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'helloController':
Unsatisfied dependency expressed through field 'helloFeignClient';
nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'com.zsh.FeignClient.HelloFeignClient':
FactoryBean threw exception on object creation;
nested exception is java.lang.IllegalStateException: Method sayHello not annotated with HTTP method type (ex. GET, POST)