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

微服务之间openfeign相互调用

  • 一、引入依赖
  • 二、在启动类上配置扫描feign 包这个重要
  • 三、服务调用 例子
  • 四、feign 远程调用请求头丢失问题
  • 五、异步情况丢失上下文
  • 六、幂等性,

一、引入依赖

 <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"));
            }
        };
    }
}

五、异步情况丢失上下文

分布式服务之间相互调用-openfeign_第1张图片

六、幂等性,

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

你可能感兴趣的:(java,架构,java,spring,boot)