为Spring任务设置线程池名称

时间:2014-11-13 09:52:30

标签: spring scheduled-tasks

我有一个相当标准的Spring 3.2应用程序,其中包含一些任务。在我的applicationContext.xml中我有

<task:annotation-driven/>

我还在代码中使用@Scheduled注释了一些方法。我想给Spring使用的线程池命名,以简化日志分析。有没有相当简单的方法来做到这一点? 感谢。

更新:工作代码:

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="1"/>
    <property name="maxPoolSize" value="5"/>
    <property name="queueCapacity" value="100"/>
    <property name="threadNamePrefix" value="executor-task-"/>
    <property name="threadGroupName" value="executor-tasks"/>
</bean>
<bean id="taskScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
    <property name="poolSize" value="5"/>
    <property name="threadNamePrefix" value="scheduled-task-"/>
    <property name="threadGroupName" value="scheduled-tasks"/>
</bean>
<task:annotation-driven executor="taskExecutor" scheduler="taskScheduler"/>

1 个答案:

答案 0 :(得分:2)

如果您希望能够指定前缀或组名,则必须自行配置TaskScheduler(适用于@Scheduled)或TaskExecutor(适用于@Async) 。如果这样做,您可以设置threadGroupNamethreadNamePrefix属性以自定义线程的名称。

<bean id="taskScheduler" class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">
    <property name="corePoolSize" value="2"/>
    <property name="maxPoolSize" value="5"/>
    <property name="queueCapacity" value="25"/>
    <property name="threadNamePrefix" value="scheduled-task"/>
    <property name="threadGroupName" value="scheduled-tasks-tg"/>
</bean>