Home  >  Article  >  Java  >  How springboot integrates dubbo to achieve group aggregation

How springboot integrates dubbo to achieve group aggregation

王林
王林forward
2023-05-11 20:43:04670browse

Consumer

yml file configuration:

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

controller class:

@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("用户未登陆");
        }
    }

Custom aggregation strategy

There is an org.apache.dubbo.rpc.cluster.Merger file in the dubbo-3.0.9.jar!/META-INF/dubbo/internal/ directory. The content of the file is as follows:

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

It declares the aggregation strategy defined by dubbo. When specifying the dubbo aggregation strategy, you can use the aggregation strategy provided by dubbo or use a custom aggregation strategy.

How to customize dubbo aggregation strategy?

Create the following directories and files in the resources directory (note: directory and file names are immutable).

How springboot integrates dubbo to achieve group aggregation

org.apache.dubbo.rpc.cluster.Merger The content of the file is as follows:

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

Custom aggregation strategy Class:

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

Provider

yml file configuration:

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

Interface and its implementation

OrderService interface:

public interface OrderService {

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

}

OrderServiceImplA implementation class:

@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 implementation class:

@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;
            }
        }
    }
}

Table structure and Data

Table structure:

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;;

Table data:

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

Demo:

How springboot integrates dubbo to achieve group aggregation

The above is the detailed content of How springboot integrates dubbo to achieve group aggregation. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete