java多线程实现发送消息

记录日常使用

package com.lee.action.service.notification.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lee.action.cache.SendFsMessageCache;
import com.lee.action.cache.SysDataDictionaryCache;
import com.lee.controller.dto.NotificationReq;
import com.lee.action.controller.dto.SendFsMessageDto;
import com.lee.action.mapper.NotificationDoMapper;
import com.lee.action.service.notification.NotificationService;

@Service
public class NotificationServiceImpl implements NotificationService {
	private Logger logger = LoggerFactory.getLogger(NotificationServiceImpl.class);
	
	@Autowired
	private NotificationDoMapper notificationDoMapper;
	
	@Autowired
	private SysDataDictionaryCache sysDataDictionaryCache;
	
	@Autowired
	private SendMessageCache sendMessageCache;
	
	//声明多线程
	private static ThreadPoolExecutor pool = new ThreadPoolExecutor(2,10,50,TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(10),
			Executors.defaultThreadFactory(),new ThreadPoolExecutor.CallerRunsPolicy());
	
	
	/**
	 * 获取人员信息
	 * 发送第三方消息
	 */
	@Override
	public void sendLeeMessage(List<String> orgIdList,NotificationReq notificationReq) {
		try {
			String url = "url";
			String accessId = "accessId";
			String accessToken = "accessToken";
			int total = 0;
			for(String item:orgIdList){
				//获取需要接受消息的总人数
				total = notificationDoMapper.getUserTotalByAll();
				//每次10000位一批次发送消息
				int time = (int)Math.ceil((double)total/10000);
				int pageIndex = 0;
				for (int i = 1; i <= time; i++) {
					pageIndex = (i - 1)*10000;
	sendLeeMessageByUserList(notificationReq,url,accessId,accessToken,item,pageIndex);
					Thread.sleep(60*1000);
				}
			}
		} catch (Exception e) {
			logger.error("NotificationServiceImpl.sendLeeMessage.Exception: ",e);
		}
	}
	
	
	public void sendLeeMessageByUserList(NotificationReq notificationReq,String url,String accessId,String accessToken, String orgId,int pageIndex){
		List<String> userList = new ArrayList<>();
			userList = notificationDoMapper.getUserListByOrgId(orgId, pageIndex, 10000);			
		if(!userList.isEmpty()){
			SendMessageDto sendFsMessageDto = new SendFsMessageDto();
			sendMessageDto.setChannel("XXX");
			sendMessageDto.setTitle(notificationReq.getMessageTitle());
			sendMessageDto.setPcUrl("");
			sendMessageDto.setAppUrl(notificationReq.getMessageUrl());
			sendMessageDto.setPutdata(notificationReq.getMessageContent());
			sendMessageDto.setUrl(url);
			sendMessageDto.setAccessId(accessId);
			sendMessageDto.setAccessToken(accessToken);
			
			
			List<String> sonList = new ArrayList<>();
			List<String> copyList = new ArrayList<>();
			for (int i = 0; i < userList.size(); i++) {
				sonList.add(userList.get(i));
				if((i+1)%1000 == 0 || i == userList.size()-1){
					try {
						copyList = deepCopy(sonList);
						pool.execute(new MyThread(sendMessageDto,copyList));
					} catch (ClassNotFoundException e) {
						logger.error("NotificationServiceImpl.sendMessageByUserList.ClassNotFoundException: ",e);
					} catch (IOException e) {
						logger.error("NotificationServiceImpl.sendMessageByUserList.IOException: ",e);
					}
					sonList.clear();
				}
				
			}
		}
	}
	
	//深度复制list集合
	public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException { 
	    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
	    ObjectOutputStream out = new ObjectOutputStream(byteOut);
	    out.writeObject(src);
	    ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
	    ObjectInputStream in = new ObjectInputStream(byteIn);
	    @SuppressWarnings("unchecked")
	    List<T> dest = (List<T>) in.readObject();
	    return dest;
	}
	
	class MyThread extends Thread {
		private SendMessageDto dto;
		private List<String> userList;
		
		public MyThread(SendMessageDto dto,List<String> userList) {
			this.dto = dto;
			this.userList = userList;
		}
		@Override
		public void run() {
			long starttime = System.currentTimeMillis();
			for (int i = 0; i < userList.size(); i++) {
				dto.setAccount(userList.get(i));
				sendMessageCache.sendFsMsg(dto);
			}
			long spendtime = System.currentTimeMillis() - starttime;
			logger.error("NotificationServiceImpl.MyThread.endTime:{}",spendtime);
		}
	}
	
	
	
	

}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值