【SpringBootAOP记录用户操作日志】3.异步任务管理器

编程

为了进少系统压力这里使用异步任务管理器来处理

线程池配置

线程相关工具类

 

/**

* 线程相关工具类.

*

* @author hekang

*/

public class Threads

{

private static final Logger logger = LoggerFactory.getLogger(Threads.class);

/**

* sleep等待,单位为毫秒

*/

public static void sleep(long milliseconds)

{

try

{

Thread.sleep(milliseconds);

}

catch (InterruptedException e)

{

return;

}

}

/**

* 停止线程池

* 先使用shutdown, 停止接收新任务并尝试完成所有已存在任务.

* 如果超时, 则调用shutdownNow, 取消在workQueue中Pending的任务,并中断所有阻塞函数.

* 如果仍人超時,則強制退出.

* 另对在shutdown时线程本身被调用中断做了处理.

*/

public static void shutdownAndAwaitTermination(ExecutorService pool)

{

if (pool != null && !pool.isShutdown())

{

pool.shutdown();

try

{

if (!pool.awaitTermination(120, TimeUnit.SECONDS))

{

pool.shutdownNow();

if (!pool.awaitTermination(120, TimeUnit.SECONDS))

{

logger.info("Pool did not terminate");

}

}

}

catch (InterruptedException ie)

{

pool.shutdownNow();

Thread.currentThread().interrupt();

}

}

}

/**

* 打印线程异常信息

*/

public static void printException(Runnable r, Throwable t)

{

if (t == null && r instanceof Future<?>)

{

try

{

Future<?> future = (Future<?>) r;

if (future.isDone())

{

future.get();

}

}

catch (CancellationException ce)

{

t = ce;

}

catch (ExecutionException ee)

{

t = ee.getCause();

}

catch (InterruptedException ie)

{

Thread.currentThread().interrupt();

}

}

if (t != null)

{

logger.error(t.getMessage(), t);

}

}

}

 

 

线程池配置

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.ScheduledThreadPoolExecutor;

import com.aoplog.springbootaoplog.util.Threads;

import org.apache.commons.lang3.concurrent.BasicThreadFactory;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

/**

* 线程池配置

*

* @author hekang

**/

@Configuration

public class ThreadPoolConfig

{

// 核心线程池大小

private int corePoolSize = 50;

/**

* 执行周期性或定时任务

*/

@Bean(name = "scheduledExecutorService")

protected ScheduledExecutorService scheduledExecutorService()

{

return new ScheduledThreadPoolExecutor(corePoolSize,

new BasicThreadFactory.Builder().namingPattern("schedule-pool-%d").daemon(true).build())

{

@Override

protected void afterExecute(Runnable r, Throwable t)

{

super.afterExecute(r, t);

Threads.printException(r, t);

}

};

}

}

 

异步任务管理器

import com.aoplog.springbootaoplog.util.SpringUtils;

import com.aoplog.springbootaoplog.util.Threads;

import java.util.TimerTask;

import java.util.concurrent.ScheduledExecutorService;

import java.util.concurrent.TimeUnit;

/**

* 异步任务管理器

*

* @author hekang

*/

public class AsyncManager

{

/**

* 操作延迟10毫秒

*/

private final int OPERATE_DELAY_TIME = 10;

/**

* 异步操作任务调度线程池

*/

private ScheduledExecutorService executor = SpringUtils.getBean("scheduledExecutorService");

/**

* 单例模式

*/

private AsyncManager(){}

private static AsyncManager me = new AsyncManager();

public static AsyncManager me()

{

return me;

}

/**

* 执行任务

*

* @param task 任务

*/

public void execute(TimerTask task)

{

executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);

}

/**

* 停止任务线程池

*/

public void shutdown()

{

Threads.shutdownAndAwaitTermination(executor);

}

}

这里我们要用到一个spring工具类

import org.springframework.aop.framework.AopContext;

import org.springframework.beans.BeansException;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;

import org.springframework.beans.factory.config.BeanFactoryPostProcessor;

import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import org.springframework.stereotype.Component;

/**

* spring工具类 方便在非spring管理环境中获取bean

*

* @author hekang

*/

@Component

public final class SpringUtils implements BeanFactoryPostProcessor

{

/** Spring应用上下文环境 */

private static ConfigurableListableBeanFactory beanFactory;

@Override

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException

{

SpringUtils.beanFactory = beanFactory;

}

/**

* 获取对象

*

* @param name

* @return Object 一个以所给名字注册的bean的实例

* @throws org.springframework.beans.BeansException

*

*/

@SuppressWarnings("unchecked")

public static <T> T getBean(String name) throws BeansException

{

return (T) beanFactory.getBean(name);

}

/**

* 获取类型为requiredType的对象

*

* @param clz

* @return

* @throws org.springframework.beans.BeansException

*

*/

public static <T> T getBean(Class<T> clz) throws BeansException

{

T result = (T) beanFactory.getBean(clz);

return result;

}

/**

* 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true

*

* @param name

* @return boolean

*/

public static boolean containsBean(String name)

{

return beanFactory.containsBean(name);

}

/**

* 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)

*

* @param name

* @return boolean

* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException

*

*/

public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException

{

return beanFactory.isSingleton(name);

}

/**

* @param name

* @return Class 注册对象的类型

* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException

*

*/

public static Class<?> getType(String name) throws NoSuchBeanDefinitionException

{

return beanFactory.getType(name);

}

/**

* 如果给定的bean名字在bean定义中有别名,则返回这些别名

*

* @param name

* @return

* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException

*

*/

public static String[] getAliases(String name) throws NoSuchBeanDefinitionException

{

return beanFactory.getAliases(name);

}

/**

* 获取aop代理对象

*

* @param invoker

* @return

*/

@SuppressWarnings("unchecked")

public static <T> T getAopProxy(T invoker)

{

return (T) AopContext.currentProxy();

}

}

 

 

异步工厂(产生任务用)

import com.aoplog.springbootaoplog.domain.SysOperLog;

import com.aoplog.springbootaoplog.service.ISysOperLogService;

import com.aoplog.springbootaoplog.util.SpringUtils;

import java.util.TimerTask;

/**

* 异步工厂(产生任务用)

*

* @author hekang

*/

public class AsyncFactory {

/**

* 操作日志记录

*

* @param operLog 操作日志信息

* @return 任务task

*/

public static TimerTask recordOper(final SysOperLog operLog) {

return new TimerTask() {

@Override

public void run() {

// 远程查询操作地点

SpringUtils.getBean(ISysOperLogService.class).insertOperlog(operLog);

}

};

}

}

 

以上是 【SpringBootAOP记录用户操作日志】3.异步任务管理器 的全部内容, 来源链接: utcz.com/z/512232.html

回到顶部