Feign是一个声明式的HTTP客户端,他的目的就是让远程调用更加简单。给远程服务发的是HTTP请求。
1.引入Open-Feign
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.编写一个被调用的接口
@RestController
@RequestMapping("coupon/coupon")
public class CouponController {
@RequestMapping("/member/list")
public R membercoupons(){
CouponEntity couponEntity = new CouponEntity();
couponEntity.setCouponName("100减1");
return R.ok().put("coupons",Arrays.asList(couponEntity));
}
}
3.远程调用的微服务模块新建一个接口
/**
* 这是一个声明式的远程调用,编写的路径以及方法名要一致
*/
@FeignClient("gulimall-coupon")
public interface CouponFeignService {
@RequestMapping("/coupon/coupon/member/list")
public R membercoupons();
}
4.开启远程调用功能
@RestController
@RequestMapping("member/member")
public class MemberController {
@Autowired
CouponFeignService couponFeignService;
@RequestMapping("/coupons")
public R test(){
MemberEntity memberEntity = new MemberEntity();
memberEntity.setNickname("柚子");
R membercoupons = couponFeignService.membercoupons();
return R.ok().put("member",memberEntity)
.put("coupons",membercoupons.get("coupons"));
}
}
5.启动类添加注解@EnableFeignClients
package com.atguigu.gulimall.member;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
//开启远程调用的注解 @EnableFeignClients
@EnableFeignClients(basePackages = "com.atguigu.gulimall.member.fegin")
@MapperScan(basePackages = "com.atguigu.gulimall.member.dao")
@EnableDiscoveryClient
@SpringBootApplication
public class GulimallMemberApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallMemberApplication.class, args);
}
}
评论