How springboot integrates dubbo to achieve group aggregation
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).
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 '主键编号', `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='订单信息表';
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 ('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);
Demo:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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

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

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

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

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

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

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.
