首页  >  文章  >  Java  >  springboot怎么整合dubbo实现组聚合

springboot怎么整合dubbo实现组聚合

王林
王林转载
2023-05-11 20:43:04695浏览

消费者

yml 文件配置:

dubbo:
  application:
    name: dubbo-gateway
  registry:
    address: zookeeper://127.0.0.1:2181
  server: true
  provider:
    timeout: 3000
  protocol:
    name: dubbo
    port: 20881

controller 类:

@RestController
@RequestMapping(value = "/order")
@Slf4j
public class OrderController {

/**
     * dubbo 的分组特性:group(指定将要聚合的分组)
     * dubbo 的聚合特性:merger(指定聚合策略)
     * 自定义策略申明文件名为:org.apache.dubbo.rpc.cluster.Merger(不可变),文件夹名:META-INF.dubbo(不可变)
     */
    @DubboReference(check = false, group = "2017,2018", merger = "page")
    private OrderService orderService;

/**
     * 查看订单信息
     *
     * @param nowPage
     * @param pageSize
     * @return
     */
    @PostMapping("/getOrderInfo")
    public ResponseVO getOrderInfo(@RequestParam(name = "nowPage", required = false, defaultValue = "1") Integer nowPage,
                                   @RequestParam(name = "pageSize", required = false, defaultValue = "5") Integer pageSize) {

        // 获取当前登陆人的信息
        String userId = CurrentUser.getUserId();

        // 使用当前登陆人获取已经购买的订单
        Page<OrderVO> page = new Page<>(nowPage,pageSize);
        if(userId != null && userId.trim().length()>0){
            Page<OrderVO> result = orderService.getOrderByUserId(Integer.parseInt(userId), page);

            return ResponseVO.success(nowPage, (int) result.getPages(),"",result.getRecords());

        }else{
            return ResponseVO.serviceFail("用户未登陆");
        }
    }

自定义聚合策略

在 dubbo-3.0.9.jar!/META-INF/dubbo/internal/ 目录下有一个 org.apache.dubbo.rpc.cluster.Merger 文件,文件内容如下:

map=org.apache.dubbo.rpc.cluster.merger.MapMerger
set=org.apache.dubbo.rpc.cluster.merger.SetMerger
list=org.apache.dubbo.rpc.cluster.merger.ListMerger
byte=org.apache.dubbo.rpc.cluster.merger.ByteArrayMerger
char=org.apache.dubbo.rpc.cluster.merger.CharArrayMerger
short=org.apache.dubbo.rpc.cluster.merger.ShortArrayMerger
int=org.apache.dubbo.rpc.cluster.merger.IntArrayMerger
long=org.apache.dubbo.rpc.cluster.merger.LongArrayMerger
float=org.apache.dubbo.rpc.cluster.merger.FloatArrayMerger
double=org.apache.dubbo.rpc.cluster.merger.DoubleArrayMerger
boolean=org.apache.dubbo.rpc.cluster.merger.BooleanArrayMerger

其中申明了 dubbo 定义的聚合策略。在指定dubbo 聚合策略时,可使用 dubbo 提供的聚合策略,也可以使用自定义的聚合策略。

如何自定义 dubbo 聚合策略?

在 resources 目录下创建以下目录及文件(注意:目录及文件名称不可变)。

springboot怎么整合dubbo实现组聚合

org.apache.dubbo.rpc.cluster.Merger 文件内容如下:

# 自定义聚合策略
page=com.stylefeng.guns.gateway.config.PageMerger

自定义聚合策略类:

package com.stylefeng.guns.gateway.config;
import com.baomidou.mybatisplus.plugins.Page;
import org.apache.dubbo.rpc.cluster.Merger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public class PageMerger implements Merger<Page> {


    @Override
    public Page merge(Page... items) {
        Page<Object> page = new Page<>();

        List<Object> records = new ArrayList<>();
        AtomicInteger total = new AtomicInteger();

        Arrays.stream(items).forEach(item -> {
            records.addAll(item.getRecords());
            total.addAndGet((int) item.getPages());
        });
        page.setRecords(records);
        page.setSize(total.get());
        return page;
    }
}

提供者

yml 文件配置:

dubbo:
  application:
    name: dubbo-order
  registry:
    address: zookeeper://127.0.0.1:2181
  server: true
  provider:
    timeout: 3000
  protocol:
    name: dubbo
    port: 20885

接口及其实现

OrderService 接口:

public interface OrderService {

    /**
     * 使用当前登陆人获取已经购买的订单
     * @param userId
     * @param page
     * @return
     */
    Page<OrderVO> getOrderByUserId(Integer userId, Page<OrderVO> page);

}

OrderServiceImplA 实现类:

@DubboService(group = "2017")
@Slf4j
public class OrderServiceImplA implements OrderService {

    @Autowired
    private MoocOrder2017TMapper moocOrder2017TMapper;

    /**
     * 使用当前登陆人获取已经购买的订单
     *
     * @param userId
     * @param page
     * @return
     */
    @Override
    public Page<OrderVO> getOrderByUserId(Integer userId, Page<OrderVO> page) {
        Page<OrderVO> result = new Page<>();
        if(userId == null){
            log.error("订单查询业务失败,用户编号未传入");
            return null;
        }else{
            List<OrderVO> ordersByUserId = moocOrder2017TMapper.getOrdersByUserId(userId,page);
            if(ordersByUserId==null && ordersByUserId.size()==0){
                result.setTotal(0);
                result.setRecords(new ArrayList<>());
                return result;
            }else{
                // 获取订单总数
                EntityWrapper<MoocOrder2017T> entityWrapper = new EntityWrapper<>();
                entityWrapper.eq("order_user",userId);
                Integer counts = moocOrder2017TMapper.selectCount(entityWrapper);
                // 将结果放入Page
                result.setTotal(counts);
                result.setRecords(ordersByUserId);

                return result;
            }
        }
    }
}

OrderServiceImplB 实现类:

@DubboService(group = "2018")
@Slf4j
public class OrderServiceImplB implements OrderService {

    @Autowired
    private MoocOrder2018TMapper moocOrder2018TMapper;

    /**
     * 使用当前登陆人获取已经购买的订单
     *
     * @param userId
     * @param page
     * @return
     */
    @Override
    public Page<OrderVO> getOrderByUserId(Integer userId, Page<OrderVO> page) {
        Page<OrderVO> result = new Page<>();
        if(userId == null){
            log.error("订单查询业务失败,用户编号未传入");
            return null;
        }else{
            List<OrderVO> ordersByUserId = moocOrder2018TMapper.getOrdersByUserId(userId,page);
            if(ordersByUserId==null && ordersByUserId.size()==0){
                result.setTotal(0);
                result.setRecords(new ArrayList<>());
                return result;
            }else{
                // 获取订单总数
                EntityWrapper<MoocOrder2018T> entityWrapper = new EntityWrapper<>();
                entityWrapper.eq("order_user",userId);
                Integer counts = moocOrder2018TMapper.selectCount(entityWrapper);
                // 将结果放入Page
                result.setTotal(counts);
                result.setRecords(ordersByUserId);

                return result;
            }
        }
    }
}

表结构及数据

表结构:

CREATE TABLE `mooc_order_2017_t` (
  `UUID` varchar(100) DEFAULT NULL COMMENT &#39;主键编号&#39;,
  `cinema_id` int DEFAULT NULL COMMENT &#39;影院编号&#39;,
  `field_id` int DEFAULT NULL COMMENT &#39;放映场次编号&#39;,
  `film_id` int DEFAULT NULL COMMENT &#39;电影编号&#39;,
  `seats_ids` varchar(50) DEFAULT NULL COMMENT &#39;已售座位编号&#39;,
  `seats_name` varchar(200) DEFAULT NULL COMMENT &#39;已售座位名称&#39;,
  `film_price` double DEFAULT NULL COMMENT &#39;影片售价&#39;,
  `order_price` double DEFAULT NULL COMMENT &#39;订单总金额&#39;,
  `order_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT &#39;下单时间&#39;,
  `order_user` int DEFAULT NULL COMMENT &#39;下单人&#39;,
  `order_status` int DEFAULT &#39;0&#39; COMMENT &#39;0-待支付,1-已支付,2-已关闭&#39;
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT=&#39;订单信息表&#39;;

CREATE TABLE `mooc_order_2018_t` (
  `UUID` varchar(100) DEFAULT NULL COMMENT &#39;主键编号&#39;,
  `cinema_id` int DEFAULT NULL COMMENT &#39;影院编号&#39;,
  `field_id` int DEFAULT NULL COMMENT &#39;放映场次编号&#39;,
  `film_id` int DEFAULT NULL COMMENT &#39;电影编号&#39;,
  `seats_ids` varchar(50) DEFAULT NULL COMMENT &#39;已售座位编号&#39;,
  `seats_name` varchar(200) DEFAULT NULL COMMENT &#39;已售座位名称&#39;,
  `film_price` double DEFAULT NULL COMMENT &#39;影片售价&#39;,
  `order_price` double DEFAULT NULL COMMENT &#39;订单总金额&#39;,
  `order_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT &#39;下单时间&#39;,
  `order_user` int DEFAULT NULL COMMENT &#39;下单人&#39;,
  `order_status` int DEFAULT &#39;0&#39; COMMENT &#39;0-待支付,1-已支付,2-已关闭&#39;
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT=&#39;订单信息表&#39;;

表数据:

INSERT INTO `guns_rest`.`mooc_order_2017_t`(`UUID`, `cinema_id`, `field_id`, `film_id`, `seats_ids`, `seats_name`, `film_price`, `order_price`, `order_time`, `order_user`, `order_status`) VALUES (&#39;329123812gnfn31&#39;, 1, 1, 2, &#39;1,2,3,4&#39;, &#39;第一排1座,第一排2座,第一排3座,第一排4座&#39;, 63.2, 126.4, &#39;2017-05-03 12:13:42&#39;, 2, 0);
INSERT INTO `guns_rest`.`mooc_order_2017_t`(`UUID`, `cinema_id`, `field_id`, `film_id`, `seats_ids`, `seats_name`, `film_price`, `order_price`, `order_time`, `order_user`, `order_status`) VALUES (&#39;310bb3c3127a4551ad72f2f3e53333c7&#39;, 1, 1, 2, &#39;9,10&#39;, &#39;第一排9座,第一排10座&#39;, 60, 120, &#39;2022-07-20 14:25:42&#39;, 2, 0);

INSERT INTO `guns_rest`.`mooc_order_2018_t`(`UUID`, `cinema_id`, `field_id`, `film_id`, `seats_ids`, `seats_name`, `film_price`, `order_price`, `order_time`, `order_user`, `order_status`) VALUES (&#39;124583135asdf81&#39;, 1, 1, 2, &#39;1,2,3,4&#39;, &#39;第一排1座,第一排2座,第一排3座,第一排4座&#39;, 63.2, 126.4, &#39;2018-02-12 11:53:42&#39;, 2, 0);

演示:

springboot怎么整合dubbo实现组聚合

以上是springboot怎么整合dubbo实现组聚合的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:yisu.com。如有侵权,请联系admin@php.cn删除