Table of Contents
Consumer
Custom aggregation strategy
How to customize dubbo aggregation strategy?
Provider
Interface and its implementation
Table structure and Data
Home Java javaTutorial How springboot integrates dubbo to achieve group aggregation

How springboot integrates dubbo to achieve group aggregation

May 11, 2023 pm 08:43 PM
dubbo springboot

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
Copy after login

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

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
Copy after login

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
Copy after login

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;
    }
}
Copy after login

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
Copy after login

Interface and its implementation

OrderService interface:

public interface OrderService {

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

}
Copy after login

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;
            }
        }
    }
}
Copy after login

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;
            }
        }
    }
}
Copy after login

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;;
Copy after login

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);
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

How to get the value in application.yml in springboot How to get the value in application.yml in springboot Jun 03, 2023 pm 06:43 PM

In projects, some configuration information is often needed. This information may have different configurations in the test environment and the production environment, and may need to be modified later based on actual business conditions. We cannot hard-code these configurations in the code. It is best to write them in the configuration file. For example, you can write this information in the application.yml file. So, how to get or use this address in the code? There are 2 methods. Method 1: We can get the value corresponding to the key in the configuration file (application.yml) through the ${key} annotated with @Value. This method is suitable for situations where there are relatively few microservices. Method 2: In actual projects, When business is complicated, logic

SpringBoot+Dubbo+Nacos development practical tutorial SpringBoot+Dubbo+Nacos development practical tutorial Aug 15, 2023 pm 04:49 PM

This article will write a detailed example to talk about the actual development of dubbo+nacos+Spring Boot. This article will not cover too much theoretical knowledge, but will write the simplest example to illustrate how dubbo can be integrated with nacos to quickly build a development environment.

See all articles