当前位置:网站首页>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 ᖘ؏؏
边栏推荐
- 106. 如何提高 SAP UI5 应用路由 url 的可读性
- In the promotion season, how to reduce the preparation time of defense materials by 50% and adjust the mentality (personal experience summary)
- untiy世界边缘的物体阴影闪动,靠近远点的物体阴影正常
- 8 Queen question
- Multi table query of MySQL - multi table relationship and related exercises
- 双链笔记 RemNote 综合评测:快速输入、PDF 阅读、间隔重复/记忆
- Useful blog links
- The network card fails to start after the cold migration of the server hard disk
- The principle of human voice transformer
- SSH login server sends a reminder
猜你喜欢

Complete deep neural network CNN training with tensorflow to complete picture recognition case 2

STM32 and motor development (from MCU to architecture design)
![【R】 [density clustering, hierarchical clustering, expectation maximization clustering]](/img/a2/b287a5878761ee22bdbd535cae77eb.png)
【R】 [density clustering, hierarchical clustering, expectation maximization clustering]

Logseq 评测:优点、缺点、评价、学习教程

正则表达式

18W word Flink SQL God Road manual, born in the sky
![[redis] cache warm-up, cache avalanche and cache breakdown](/img/df/81f38087704de36946b470f68e8004.jpg)
[redis] cache warm-up, cache avalanche and cache breakdown
![[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]](/img/47/78d9dd098dcb894ba1f459873d5f52.png)
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [sqlserver2012 comprehensive exercise]

Introduction to the implementation principle of rxjs observable filter operator

已解决(机器学习中查看数据信息报错)AttributeError: target_names
随机推荐
Cadre de logback
Flutter动态化 | Fair 2.5.0 新版本特性
The difference between session and cookie
The R language GT package and gtextras package gracefully and beautifully display tabular data: nflreadr package and gt of gtextras package_ plt_ The winloss function visualizes the win / loss values
JS 将伪数组转换成数组
Smbms project
MyCms 自媒体商城 v3.4.1 发布,使用手册更新
Comprehensive evaluation of double chain notes remnote: fast input, PDF reading, interval repetition / memory
The principle of human voice transformer
Server coding bug
Internet of things completion -- (stm32f407 connects to cloud platform detection data)
CVPR 2022 image restoration paper
Mysql database basic operation - regular expression
Flink SQL knows why (12): is it difficult to join streams? (top)
8 Queen question
Slf4j log facade
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]
Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g
Flink code is written like this. It's strange that the window can be triggered (bad programming habits)
人身变声器的原理