1、引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、编写一个接口需要远程调用服务(例: A服务需要调用B服务,这个接口就写在B服务里面)
A服务的代码
@FeignClient("B服务在nacos注册的服务名")
public interface CouponFeignService {
//需要调用的服务暴露的controller ,也就是A服务要调用的B服务的controller
@RequestMapping("/coupon/get")
R get();
}
B服务的代码
@RestController
@RequestMapping("/coupon")
public class CouponController {
@Autowired
private CouponService couponService;
@RequestMapping("/get")
public R get(){
CouponEntity entity = new CouponEntity();
entity.setCouponName("满50减10");
return R.ok().put("coupon", Arrays.asList(entity));
}
3、开启openFeign的远程调用功能(启动类加上注解 @EnableFeignClients)
@EnableFeignClients(basePackages = "com.xxx.member.feign") //这个basePackages指的是当前服务的feign的包
@SpringBootApplication
@EnableDiscoveryClient
public class MemberApplication {
public static void main(String[] args) {
SpringApplication.run(MemberApplication.class, args);
}
}