概述
Feign是简化Java HTTP客户端开发的工具,类似于RPC,但它的作用是用于彼此间服务的调用
Feign是在Eureka服务下进行的,为此你需要先搭建Eureka服务
demo
项目结构如下,演示一下ordereurekaclient调用orderbase的案例
OrderBase服务
配置pom,引入feign依赖包
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
配置文件
server:
port: 8085
spring:
application:
name: order-base
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/world
username: root
password: a233
eureka:
client:
service-url: #Eureka客户端和Eureka服务端进行交互的地址
defaultZone: http://127.0.0.1:8082/eureka/
instance:
prefer-ip-address: true
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
启动类
@SpringBootApplication
@EnableEurekaClient
public class BaseApplication {
public static void main(String[] args) {
SpringApplication.run(BaseApplication.class);
}
}
服务类,通常是controller
@RestController
@RequestMapping("base")
public class orderbase {
@RequestMapping(value = "/label/{id}",method = RequestMethod.GET)
public String findId(String id){
return "cc";
}
}
ordereurekaclient服务
pom配置
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
application配置
server:
port: 8083
spring:
application:
name: order-client
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/world
username: root
password: a233
eureka:
client:
service-url: #Eureka客户端和Eureka服务端进行交互的地址
defaultZone: http://127.0.0.1:8082/eureka/
instance:
prefer-ip-address: true
mybatis-plus:
mapper-locations: classpath:/mapper/*.xml
启动类:增加了@EnableDiscoveryClient和@EnableFeignClients两个注解
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
public class EurekaClientApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientApplication.class);
}
}
Feign类
@FeignClient("order-base")
public interface Feigntest {
@RequestMapping(value = "/base/label/{id}",method = RequestMethod.GET)
public String findId(@PathVariable("id") String id);
}
服务调用类:把Feign注入进来,调用就可以了
@RequestMapping("user")
@RestController
public class UserController {
@Autowired
private Feigntest feigntest;
@RequestMapping(value = "/label/{labelid}")
public String findBaseId(@PathVariable String labelid){
String id = feigntest.findId(labelid);
return id;
}
}
可以看到如下结果