OpenFeign学习,谷粒商城P22
个人学习笔记以及操作流程,本篇文章内容记录在微服务A中调用微服务B的接口实现过程。
需要注意的是:
(1)由于 nacos-discovery 已包含了 Ribbon,因此无需引入该依赖
(2)但从 2022.0.1 版本的 Spring Cloud 开始,需要引入 loadbalancer 才能使用 LoadBalanced 的注解
(3)因此只需要单独引入 OpenFeign 的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 在CouponController中创建测试。
@RequestMapping("/member/list")
public R membercoupons(){
CouponEntity couponEntity = new CouponEntity();
couponEntity.setCouponName("满99-20");
return R.ok().put("coupons",couponEntity);
}
- 在gulimall-member中创建包com.atguigu.gulimail.member.fegin,创建接口CouponsFeignService,值得注意的是
@FeignClient
中,从源码上来看,name和value两者的作用是一致的,都是根据名称从nacos获取服务,在本地环境中如果配置了url,则会从忽略name,直接从url中进行请求。
public @interface FeignClient {
@AliasFor("name")
String value() default "";
String contextId() default "";
@AliasFor("value")
String name() default "";
/** @deprecated */
@Deprecated
String qualifier() default "";
String[] qualifiers() default {};
String url() default "";
boolean decode404() default false;
Class<?>[] configuration() default {};
Class<?> fallback() default void.class;
Class<?> fallbackFactory() default void.class;
String path() default "";
boolean primary() default true;
}
@FeignClient(value = "gulimall-coupon")
public interface CouponsFeignService {
@RequestMapping("/coupon/coupon/member/list")
public R membercoupons();
}
- 在GulimailMemberApplication中添加注解
@EnableFeignClients(basePackages = {"com.atguigu.gulimall.member.fegin"})
,此处配置的作用是在启动时扫描fegin的路径,从而获取其中的service。
@EnableFeignClients(basePackages = {"com.atguigu.gulimail.member.fegin"})
@EnableDiscoveryClient
@SpringBootApplication
public class GulimailMemberApplication {
public static void main(String[] args) {
SpringApplication.run(GulimailMemberApplication.class, args);
}
}
- 最后在MemberController中添加测试。
@RequestMapping("/coupons")
public R test(){
MemberEntity memberEntity = new MemberEntity();
memberEntity.setNickname("小泉李");
R membercoupons = couponsFeignService.membercoupons();
return R.ok().put("member",memberEntity).put("coupons",membercoupons);
}
最终返回调用http://localhost:200/member/member/coupons
返回结果。
{"msg":"success","code":0,"coupons":{"msg":"success","code":0,"coupons":{"id":null,"couponType":null,"couponImg":null,"couponName":"满99-20","num":null,"amount":null,"perLimit":null,"minPoint":null,"startTime":null,"endTime":null,"useType":null,"note":null,"publishCount":null,"useCount":null,"receiveCount":null,"enableStartTime":null,"enableEndTime":null,"code":null,"memberLevel":null,"publish":null}},"member":{"id":null,"levelId":null,"username":null,"password":null,"nickname":"小泉桑","mobile":null,"email":null,"header":null,"gender":null,"birth":null,"city":null,"job":null,"sign":null,"sourceType":null,"integration":null,"growth":null,"status":null,"createTime":null}}