openFeign是springcloud中一个关于服务调用的重要组件,介绍一下这个组件的使用,这里的注册中心使用的是eureka
添加核心依赖
<!--eureka的依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--openFeign的依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
配置properties文件
server.port=端口号
#是否将自己注册到eureka
eureka.client.register-with-eureka=false
#注册中心url
eureka.client.service-url.defaultZone=http://eureka7002.com:7002/eureka/,http://eureka7001.com:7001/eureka/
主启动类
主启动类添加注解@EnableFeignClients
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class CloudConsumerFeignOrder9001Application {
public static void main(String[] args) {
SpringApplication.run(CloudConsumerFeignOrder9001Application.class, args);
}
}
核心代码的编写
在完成以上相关配置后就是核心代码的编写,openFeign整合了ribbon,并在此基础上进行了进一步的封装,写出来的代码更加符合面向接口编程
- 首先是编写相关接口
在接口中使用注解@FeignClient
完成接口对某一对外暴露的服务之间的映射
在方法上面使用注解@RequestMapping
让接口中的方法映射到服务提供方的某一具体实现方法
@Component
//CLOUD-PAYMENT-SERVICE为服务名称
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
///payments/get/{id}为服务暴露的uri
@RequestMapping("/payments/get/{id}")
JsonResult<Payment> getById(@PathVariable("id")Long id);
}
- 编写controller
使用注解@Component
完成对接口类的注入之后就可以编写controller类了
@RestController
public class MyController {
@Resource
private PaymentFeignService paymentFeignService;
@RequestMapping("/consumer/get/{id}")
public JsonResult<Payment> get(@PathVariable("id") Long id){
return paymentFeignService.getById(id);
}
}