标签:work dem desc icon tor 执行 注入 reg xtend
package com.example.spring.async.config; import java.util.concurrent.Executors; import javax.naming.NamingException; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mock.jndi.SimpleNamingContextBuilder; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.DefaultManagedTaskScheduler; @Configuration public class JndiConfig { @Bean @Qualifier("jndiTaskScheduler") TaskScheduler taskScheduler () { //正常情况下,jndi是寻找其它进程提供的服务,这里在本进程中注册只是为了测试效果 registerJndi(); //这个类会使用jndi从服务器上寻找服务,可能由其它jvm进程提供线程池。使用的名字为注册名:java:comp/DefaultManagedScheduledExecutorService return new DefaultManagedTaskScheduler(); } /** * 使用jndi将线程池注入,下面的名字作为寻址的标识:java:comp/DefaultManagedScheduledExecutorService * */ public void registerJndi() { SimpleNamingContextBuilder b = new SimpleNamingContextBuilder(); b.bind("java:comp/DefaultManagedScheduledExecutorService", Executors.newScheduledThreadPool(5)); try { b.activate(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } } }
使用类:
package com.example.spring.async; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.scheduling.TaskScheduler; import org.springframework.stereotype.Service; import com.example.spring.MyLog; /** * 测试通过jndi获取的线程池执行器来执行服务 * @DESC * @author guchuang * */ @Service public class JndiThreadPool { @Autowired @Qualifier("jndiTaskScheduler") TaskScheduler taskScheduler; public void runTask () { taskScheduler.scheduleWithFixedDelay((Runnable) () -> { MyLog.info("running "); }, 1000L); } }
测试类:
package com.example.spring.async; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.example.spring.BaseDemoApplicationTest; import com.example.spring.MyLog; import com.example.spring.async.JndiThreadPool; public class JndiThreadPoolTest extends BaseDemoApplicationTest { @Autowired JndiThreadPool jndi; @BeforeClass public static void setUpBeforeClass() throws Exception { } @Before public void setUp() throws Exception { } @Test public void testRunTask() { jndi.runTask(); MyLog.sleep(5000); } }
spring 线程池执行器DefaultManagedTaskScheduler之jndi
标签:work dem desc icon tor 执行 注入 reg xtend
原文地址:https://www.cnblogs.com/gc65/p/11183848.html