亲宝软件园·资讯

展开

springboot 整合 dubbo

久违の欢喜 人气:0

消费者

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 目录下创建以下目录及文件(注意:目录及文件名称不可变)。

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

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

表数据:

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 ('329123812gnfn31', 1, 1, 2, '1,2,3,4', '第一排1座,第一排2座,第一排3座,第一排4座', 63.2, 126.4, '2017-05-03 12:13:42', 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 ('310bb3c3127a4551ad72f2f3e53333c7', 1, 1, 2, '9,10', '第一排9座,第一排10座', 60, 120, '2022-07-20 14:25:42', 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 ('124583135asdf81', 1, 1, 2, '1,2,3,4', '第一排1座,第一排2座,第一排3座,第一排4座', 63.2, 126.4, '2018-02-12 11:53:42', 2, 0);

演示:

加载全部内容

相关教程
猜你喜欢
用户评论