当前位置:网站首页>ThreadPoolExecutor realizes multi-threaded concurrency and obtains the return value (elegant and concise way)
ThreadPoolExecutor realizes multi-threaded concurrency and obtains the return value (elegant and concise way)
2022-07-03 13:31:00 【MarquiS_ houzf】
Preface
Database information query is the most common work problem . Generally, it is a single thread sequential query , In this way, the total query time is the sum of all query times , It takes a long time . If you use multi-threaded parallel query , Then the time becomes the longest for a single function to query . Time is greatly shortened . According to Alibaba development specification , To rewrite ThreadPoolExecutor Thread pool , Improve controllability . Database queries also require the return value of the active thread after execution , In this way, it is not only necessary to rewrite ThreadPoolExecutor, Have to rewrite CallAble Also get the return value (RunAble Getting the return value... Is not supported ). Here is an example of elegant and concise implementation of the above functions .
scene : Realize multithreading concurrency and get the return value
Code :
Because everybody contorller and dao Layers are familiar , I am not involved in their change , Just omit . Write directly what needs to be changed serviceImpl.
serviceImpl layer :
package com.asiainfo.cem.uaa.service;
import com.asiainfo.cem.common.util.ParallelUtil;
import com.asiainfo.cem.common.util.ParallelUtil.ParallelJob;
import com.asiainfo.cem.uaa.common.UaaConstants;
import com.asiainfo.cem.uaa.domain.LoginUserDTO;
import com.asiainfo.cem.uaa.domain.SysUser;
import com.asiainfo.cem.uaa.dao.SysPermissionDao;
import com.asiainfo.cem.uaa.dao.SysRoleDao;
import com.asiainfo.cem.uaa.dao.SysUserDao;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
/**
*@program: cem
*@description:
*@author: houzf
*/
@Service
public class UserServiceDetail implements UserDetailsService {
@Autowired
private SysUserDao sysUserDao;
@Autowired
private SysRoleDao sysRoleDao;
@Autowired
private SysPermissionDao sysPermissionDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
SysUser userDO = sysUserDao.findByUsername(username);
if (userDO == null) {
throw new UsernameNotFoundException(MessageFormat.format("{0} is empty.", username));
}
ParallelJob<Set<String>> getRoleCodeByUserNameJob = new ParallelJob<Set<String>>()
.setFunction(() -> sysRoleDao.getRoleCodeByUserName(username));
ParallelJob<Set<String>> getPermissionByUserNameJob = new ParallelJob<Set<String>>()
.setFunction(() -> sysPermissionDao.getPermissionByUserName(username));
ParallelJob<Set<String>> getPermissionCodeByUserNameJob = new ParallelJob<Set<String>>()
.setFunction(() -> sysPermissionDao.getPermissionCodeByUserName(username));
ParallelUtil.execute(getRoleCodeByUserNameJob, getPermissionByUserNameJob,getPermissionCodeByUserNameJob);
Set<String>roles=getRoleCodeByUserNameJob.getResutl();
HashMap map=new HashMap(roles.size());
if (roles.size()!=0){
for (String roleCode:roles){
List<String>permissionCodeList=new ArrayList<>();
if(UaaConstants.ADMIN.equals(roleCode)||UaaConstants.SUPADMIN.equals(roleCode)){
permissionCodeList.add(UaaConstants.ALL_PERMISSION);
}else {
permissionCodeList = sysPermissionDao.getPermissionByRoleCode(roleCode);
}
map.put(roleCode,permissionCodeList);
}
}
LoginUserDTO loginUserDTO = new LoginUserDTO()
.setPermissionCodes(getPermissionCodeByUserNameJob.getResutl())
.setRoles(roles)
.setRoleAndPermissions(map)
.setUser(userDO);
return loginUserDTO;
}
}
This is a key tool class for concurrent tasks , Mainly using generics and thread pools , Elegant and concise problem solving . It can be applied to the whole project .
Util:
package com.asiainfo.cem.common.util;
import java.util.Arrays;
import java.util.function.Supplier;
import lombok.Data;
import lombok.NonNull;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
/**
*@program: cem-service
*@description: Parallel task tool class
*@author: houzf
*/
@Slf4j
public class ParallelUtil {
@FunctionalInterface
public interface ParallelFunction<T> extends Supplier<T> {
}
@Data
@Accessors(chain = true)
public static class ParallelJob<T> {
private ParallelFunction<T> function;
private T resutl;
}
public static void execute(@NonNull ParallelJob... jobs) {
Arrays.stream(jobs).parallel().forEach(job ->
job.setResutl(job.getFunction().get())
);
}
}
For another serviceImpl Example
package com.asiainfo.cem.governmental.service.impl;
import com.asiainfo.cem.common.domain.CommonResult;
import com.asiainfo.cem.common.util.ParallelUtil;
import com.asiainfo.cem.common.utils.GetPointSetUtil;
import com.asiainfo.cem.common.utils.PageUtil;
import com.asiainfo.cem.common.utils.StringUtil;
import com.asiainfo.cem.governmental.dao.CemGovernmentalDataMapper;
import com.asiainfo.cem.governmental.domain.dto.GovernmentalScoreInfo;
import com.asiainfo.cem.governmental.domain.query.GovernmentalQueryAllScoreParam;
import com.asiainfo.cem.governmental.domain.query.GovernmentalQueryAllScoreCountParam;
import com.asiainfo.cem.governmental.domain.vo.GovernmentalQueryAllScoreVo;
import com.asiainfo.cem.governmental.service.interfaces.ICemGovernmentalServiceCSV;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.sql.Timestamp;
import java.util.concurrent.*;
@Service
@Transactional
@Slf4j(topic = "Governmental-PERCEPTION")
public class ICemGovernmentalServiceCSVImpl implements ICemGovernmentalServiceCSV {
private static final Logger logger = LoggerFactory.getLogger("GOVERNMENTAL_THREAD_TASK");
@Autowired
private CemGovernmentalDataMapper cemGovermentalDaoMapper;
private static ExecutorService threadPool;
/**
* @param params
* @description: Query the relevant scores of government and enterprise customer satisfaction
* @return: {@link CommonResult}
* @author houzf
*/
@Override
public CommonResult queryAllPerceptionScore(GovernmentalQueryAllScoreVo params) {
Integer pageNum = 1;
if (!StringUtil.isBlank(params.getPageNum())) {
pageNum = Integer.valueOf(params.getPageNum());
}
Integer pageSize = Integer.valueOf(params.getPageSize());
String order = params.getOrder();
String p1 = params.getP1();
String p2 = params.getP2();
String p3 = params.getP3();
String p4 = params.getP4();
Timestamp startTime = Timestamp.valueOf(params.getStartTime() + " 00:00:00");
Timestamp endTime = Timestamp.valueOf(params.getStartTime() + " 23:59:59");
Integer pageIndex = (pageNum - 1) * pageSize;
String[] points = GetPointSetUtil.lngLatSwap(new String[]{p1, p2, p3, p4});
double[] pointSetScope = GetPointSetUtil.
getPointSetScope(new String[]{points[0], points[1], points[2], points[3]});
double maxLongitude = pointSetScope[0];
double minLongitude = pointSetScope[1];
double maxLatitude = pointSetScope[2];
double minLatitude = pointSetScope[3];
GovernmentalQueryAllScoreCountParam perceptionQueryAllScoreCountParam =
GovernmentalQueryAllScoreCountParam.builder()
.maxLongitude(maxLongitude)
.minLongitude(minLongitude)
.maxLatitude(maxLatitude)
.minLatitude(minLatitude)
.startTime(startTime)
.endTime(endTime)
.build();
GovernmentalQueryAllScoreParam perceptionQueryAllScoreParam =
GovernmentalQueryAllScoreParam.builder()
.maxLongitude(maxLongitude)
.minLongitude(minLongitude)
.maxLatitude(maxLatitude)
.minLatitude(minLatitude)
.startTime(startTime)
.endTime(endTime)
.pageSize(pageSize)
.pageIndex(pageIndex)
.order(order)
.build();
// Parallel queries
ParallelUtil.ParallelJob<Integer> total
= new ParallelUtil.ParallelJob<Integer>().setFunction(() ->
cemGovermentalDaoMapper.getQueryAllPerceptionScoreListCount(perceptionQueryAllScoreCountParam));
ParallelUtil.ParallelJob<List<GovernmentalScoreInfo>> dataList
= new ParallelUtil.ParallelJob<List<GovernmentalScoreInfo>>().setFunction(() ->
cemGovermentalDaoMapper.queryAllPerceptionScore(perceptionQueryAllScoreParam));
ParallelUtil.execute(total, dataList);
PageUtil<GovernmentalScoreInfo> pageUtil = new PageUtil<>();
pageUtil.setPageNum(pageNum);
pageUtil.setPageSize(pageSize);
pageUtil.setTotal(Integer.valueOf(total.getResutl()));
pageUtil.setData(dataList.getResutl());
pageUtil.getPageCount();
pageUtil.setCurrentTime(System.currentTimeMillis());
return CommonResult.ok(pageUtil);
}
}
The main thing is to see “// Parallel queries ” Next one . You can use any type of return value , Such as Integer perhaps List.
If it helps you , Please pay attention to , give the thumbs-up , Collection , Three even .
Your affirmation , It's my motivation . I wish the Chinese nation an early rejuvenation ! Thank you. .
؏؏ᖗ A kind of ◡ A kind of ᖘ؏؏
边栏推荐
- The shortage of graphics cards finally came to an end: 3070ti for more than 4000 yuan, 2000 yuan cheaper than the original price, and 3090ti
- MapReduce implements matrix multiplication - implementation code
- 服务器硬盘冷迁移后网卡无法启动问题
- Flink SQL knows why (XIV): the way to optimize the performance of dimension table join (Part 1) with source code
- 已解决(机器学习中查看数据信息报错)AttributeError: target_names
- 人身变声器的原理
- untiy世界边缘的物体阴影闪动,靠近远点的物体阴影正常
- regular expression
- Mysql database basic operation - regular expression
- Flink SQL knows why (7): haven't you even seen the ETL and group AGG scenarios that are most suitable for Flink SQL?
猜你喜欢
Detailed explanation of multithreading
18W word Flink SQL God Road manual, born in the sky
【电脑插入U盘或者内存卡显示无法格式化FAT32如何解决】
常见的几种最优化方法Matlab原理和深度分析
Box layout of Kivy tutorial BoxLayout arranges sub items in vertical or horizontal boxes (tutorial includes source code)
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter III exercises]
Libuv Library - Design Overview (Chinese version)
Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
Elk note 24 -- replace logstash consumption log with gohangout
Flink SQL knows why (XV): changed the source code and realized a batch lookup join (with source code attached)
随机推荐
PostgreSQL installation
The shadow of the object at the edge of the untiy world flickers, and the shadow of the object near the far point is normal
Reptile
untiy世界边缘的物体阴影闪动,靠近远点的物体阴影正常
The difference between stratifiedkfold (classification) and kfold (regression)
CVPR 2022 | 美团技术团队精选6篇优秀论文解读
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]
刚毕业的欧洲大学生,就能拿到美国互联网大厂 Offer?
Resolved (error in viewing data information in machine learning) attributeerror: target_ names
Kivy tutorial how to load kV file design interface by string (tutorial includes source code)
双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
Servlet
Understanding of CPU buffer line
SSH login server sends a reminder
Setting up remote links to MySQL on Linux
Logseq evaluation: advantages, disadvantages, evaluation, learning tutorial
Task6: using transformer for emotion analysis
Swiftui development experience: the five most powerful principles that a programmer needs to master
Road construction issues
使用Tensorflow进行完整的深度神经网络CNN训练完成图片识别案例2