当前位置:网站首页>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 ᖘ؏؏
边栏推荐
- Logseq evaluation: advantages, disadvantages, evaluation, learning tutorial
- 开始报名丨CCF C³[email protected]奇安信:透视俄乌网络战 —— 网络空间基础设施面临的安全对抗与制裁博弈...
- Flink SQL knows why (XV): changed the source code and realized a batch lookup join (with source code attached)
- 71 articles on Flink practice and principle analysis (necessary for interview)
- Flink SQL knows why (19): the transformation between table and datastream (with source code)
- Resource Cost Optimization Practice of R & D team
- Ubuntu 14.04 下开启PHP错误提示
- Flink SQL knows why (17): Zeppelin, a sharp tool for developing Flink SQL
- Flick SQL knows why (10): everyone uses accumulate window to calculate cumulative indicators
- File uploading and email sending
猜你喜欢
Today's sleep quality record 77 points
When updating mysql, the condition is a query
Solve system has not been booted with SYSTEMd as init system (PID 1) Can‘t operate.
When we are doing flow batch integration, what are we doing?
MySQL_ JDBC
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]
stm32和电机开发(从mcu到架构设计)
Flink SQL knows why (VIII): the wonderful way to parse Flink SQL tumble window
[email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g"/>
Start signing up CCF C ³- [email protected] chianxin: Perspective of Russian Ukrainian cyber war - Security confrontation and sanctions g
Mysql database basic operation - regular expression
随机推荐
Asp. Net core1.1 without project JSON, so as to generate cross platform packages
MySQL
[today in history] July 3: ergonomic standards act; The birth of pioneers in the field of consumer electronics; Ubisoft releases uplay
Internet of things completion -- (stm32f407 connects to cloud platform detection data)
Server coding bug
Mycms we media mall v3.4.1 release, user manual update
2022-02-13 plan for next week
父亲和篮球
Road construction issues
[Database Principle and Application Tutorial (4th Edition | wechat Edition) Chen Zhibo] [Chapter IV exercises]
阿南的疑惑
DQL basic query
正则表达式
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
网上开户哪家证券公司佣金最低,我要开户,网上客户经理开户安全吗
Swiftui development experience: the five most powerful principles that a programmer needs to master
stm32和电机开发(从mcu到架构设计)
已解决TypeError: Argument ‘parser‘ has incorrect type (expected lxml.etree._BaseParser, got type)
In the promotion season, how to reduce the preparation time of defense materials by 50% and adjust the mentality (personal experience summary)
Complete deep neural network CNN training with tensorflow to complete picture recognition case 2