第一步导入jar包
<dependencies>
<!--引入Eureka的客户端依赖,不包含springboot-start-web,所以要单独引入-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--引入springboot-start-web依赖,必须引入-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入OpenFeign依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
第二步:编写启动类
@EnableFeignClients:此注解会在启动时扫描当前类同级以及以下所有Feign接口,进行动态代理创建实现类
@SpringBootApplication
@EnableEurekaClient // 表示Eureka客户端
@EnableFeignClients // 开启OpenFeign支持
public class PayServerApp {
public static void main(String[] args) {
SpringApplication.run(PayServerApp.class, args);
}
}
第三步:编写配置文件
spring:
application: # 指定此服务的应用名称
name: order-server
feign:
hystrix:
enabled: true #开启熔断支持
第四步:编写Feign接口,提供服务调用
建议写一个公共的feign-api什么模块需要就直接调用
@FeignClient("user-server") // 指定需要调用的服务的应用名称
@RequestMapping("/user")
public interface UserFeignClient {
/**
* OpenFeign调用user服务接口,默认底层会帮助我们创建动态代理实现类,会使用RestTemplate进行调用
* @param id
* @return
*/
@GetMapping("/{id}")
User getById(@PathVariable("id") Long id);
}
第五步:编写order服务接口,使用feign调用user服务
@RestController
@RequestMapping("order")
public class OrderController {
@Autowired
private UserFeignClient userFeignClient;
@GetMapping("{orderId}")
public User queryOrderByUserId(@PathVariable("orderId") Long orderId) {
return userFeignClient.queryById(orderId);
}