分布式服务之间相互调用-openfeign

7 篇文章 0 订阅

一、引入依赖

 <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

二、在启动类上配置扫描feign 包这个重要

@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients(basePackages = "com.yang.yimall.user.feign") //fegin包扫描
public class YimallUserApplication {

    public static void main(String[] args) {
        SpringApplication.run(YimallUserApplication.class, args);
    }

}

三、服务调用 例子

A服务调用B服务 在A新建feign包,在B服务controller然后写上接口
B服务

@RestController
@AllArgsConstructor
@RequestMapping("/goods/manager/productCategory")
public class ProductCategoryController extends AbstractCrudController {
    private final ProductCategoryService productCategoryService;

    @RequestMapping("/listWithTree")
    public Ret<List<ProductCategory>> listWithTree() {
        List<ProductCategory> categoryEntities = productCategoryService.listWithTree();
        return Ret.success("", categoryEntities);
   			 }
    }

A服务调用B服务接口

@FeignClient(value = "yimall-product")
public interface ProductFeignService {

    @RequestMapping("/goods/manager/productCategory/listWithTree")
    Ret<List<ProductCategory>> listWithTree();

}

四、feign 远程调用请求头丢失问题

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class ShoppingFeignConfig {

    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
//                getRequestAttributes也行
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
                HttpServletRequest httpServletRequest = requestAttributes.getRequest();
                //老请求 Cookie 给新请求
                requestTemplate.header("Authorization", httpServletRequest.getHeader("Authorization"));
            }
        };
    }
}

五、异步情况丢失上下文

在这里插入图片描述

六、幂等性,

1、token+redis
2、锁机制,version
update t_sku set stock=stock - #{num} where goods_id = #{goodsId} and vsersion = #{version}
3、分布式锁 redis可以
4、redis + set 防重复
5 全局请求唯一ID

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值