1. public class RtmpSpyingTests extends AbstractTransactionalJUnit4SpringContextTests {
  2. @Autowired
  3. ThreadPoolTaskExecutor rtmpSpyingTaskExecutor;
  4.  
  5. @Autowired
  6. ApplicationContext ctx;
  7.  
  8. @Autowired
  9. RtmpSourceRepository rtmpRep;
  10.  
  11. @Test
  12. public void test() {
  13. RtmpSource rtmpSourceSample = new RtmpSource("test");
  14.  
  15. rtmpRep.save(rtmpSourceSample);
  16. rtmpRep.flush();
  17.  
  18. List<RtmpSource> rtmpSourceList = rtmpRep.findAll(); // Here I get a list containing rtmpSourceSample
  19.  
  20. RtmpSpyingTask rtmpSpyingTask = ctx.getBean(RtmpSpyingTask.class,
  21. "arg1","arg2");
  22. rtmpSpyingTaskExecutor.execute(rtmpSpyingTask);
  23.  
  24. }
  25. }
  26.  
  27. public class RtmpSpyingTask implements Runnable {
  28.  
  29. @Autowired
  30. RtmpSourceRepository rtmpRep;
  31.  
  32. String nameIdCh;
  33. String rtmpUrl;
  34.  
  35. public RtmpSpyingTask(String nameIdCh, String rtmpUrl) {
  36. this.nameIdCh = nameIdCh;
  37. this.rtmpUrl = rtmpUrl;
  38. }
  39.  
  40. public void run() {
  41. // Here I should get a list containing rtmpSourceSample, but instead of that
  42. // I get an empty list
  43. List<RtmpSource> rtmpSource = rtmpRep.findAll();
  44. }
  45. }
  46.  
  47. 应该用
  48. @Service
  49. public class AsyncTransactionService {
  50.  
  51. @Autowired
  52. RtmpSourceRepository rtmpRep;
  53.  
  54. @Transactional(readOnly = true)
  55. public List<RtmpSource> getRtmpSources() {
  56. return rtmpRep.findAll();
  57. }
  58.  
  59. @Transactional(propagation = Propagation.REQUIRES_NEW)
  60. public void insertRtmpSource(RtmpSource rtmpSource) {
  61. rtmpRep.save(rtmpSource);
  62. }
  63. }

或者

用内部类。

  1. package com.italktv.platform.audioDist.service;
  2.  
  3. import java.io.Serializable;
  4. import java.time.LocalDateTime;
  5. import java.util.List;
  6. import java.util.Map;
  7. import java.util.Map.Entry;
  8. import java.util.Random;
  9. import java.util.concurrent.TimeUnit;
  10.  
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.beans.factory.annotation.Value;
  15. import org.springframework.scheduling.annotation.Scheduled;
  16. import org.springframework.stereotype.Component;
  17.  
  18. import com.italktv.platform.audioDist.mongo.CustomerRepository;
  19. import com.italktv.platform.audioDist.mongo.PlayUrl;
  20. import com.italktv.platform.audioDist.mongo.PlayUrl.MyUrl;
  21. import com.italktv.platform.audioDist.mongo.PlayUrlRepository;
  22. import com.italktv.platform.audioDist.mysql.SubSet;
  23. import com.italktv.platform.audioDist.mysql.UserRepository;
  24. import com.italktv.platform.audioDist.task.MyTask;
  25. import com.italktv.platform.audioDist.task.TaskManager;
  26.  
  27. @Component
  28. public class ScheduleJobs {
  29. private static final Logger log = LoggerFactory.getLogger(ScheduleJobs.class);
  30.  
  31. public final static long SECOND = 1 * 1000;
  32. LocalDateTime nowDate = LocalDateTime.now();
  33.  
  34. @Autowired
  35. // This means to get the bean called userRepository
  36. // Which is auto-generated by Spring, we will use it to handle the data
  37. private UserRepository userRepository;
  38.  
  39. @Autowired
  40. private PlayUrlRepository repository;
  41. @Autowired
  42. private CustomerRepository cc;
  43.  
  44. @Autowired
  45. private UserRepository user;
  46.  
  47. @Autowired
  48. TaskManager taskManager;
  49.  
  50. @Scheduled(fixedRate = SECOND * 400)
  51. public void fixedRateJob() {
  52. nowDate = LocalDateTime.now();
  53. System.out.println("=== start distribution: " + nowDate);
  54. dotask();
  55. }
  56.  
  57. // @PostConstruct
  58. // public void init() {
  59. //
  60. // taskManager = new TaskManager();
  61. // taskManager.init();
  62. // }
  63. //
  64. // @PreDestroy
  65. // void destroy() {
  66. // taskManager.destroy();
  67. // }
  68.  
  69. void dotask() {
  70.  
  71. Map<Integer, List<SubSet>> map = userRepository.getUploadFileMap();
  72. for (Entry<Integer, List<SubSet>> subject : map.entrySet()) {
  73. int subjectId = subject.getKey();
  74. log.info(" subject id:" + subjectId);
  75. List<SubSet> allsub = subject.getValue();
  76. for (SubSet item : allsub) {
  77. log.info(" sub:" + item.toString());
  78. taskManager.add(new MessagePublish(item.id, item.path));
  79. }
  80.  
  81. //wait them finished
  82. //TODO:
  83.  
  84. //update subject status
  85. //TODO
  86.  
  87. }
  88.  
  89. }
  90.  
  91. ////////////////////////内部类////////////////////////
  92. public class MessagePublish extends MyTask implements Serializable{
  93. public MessagePublish() {
  94. super();
  95. }
  96. public MessagePublish(int id,String name ){
  97. this.srcFile = name;
  98. this.partId=id;
  99. }
  100.  
  101. @Value("${platform.audio.dist.domain}") private String domain;
  102.  
  103. @Override
  104. public String call() {
  105. System.out.println(srcFile + " is uploading...");
  106. try {
  107. //获取消息发布的区域
  108. TimeUnit.SECONDS.sleep(new Random().nextInt(10)+1);
  109. } catch (Exception e) {
  110. // TODO Auto-generated catch block
  111. e.printStackTrace();
  112. }
  113. System.out.println(srcFile + " uploaded.");
  114.  
  115. //2.RECORD TO MONGO DB
  116. PlayUrl play=new PlayUrl();
  117. play.programid="programid fake"+ "";
  118. play.domain=domain;
  119. play.protocol="HTTP";
  120. MyUrl myurl=new MyUrl();
  121. myurl.high="http://xxx.xxx/xi//";
  122. play.url=myurl;
  123. repository.save(play);
  124. //TODO:
  125.  
  126. //IF FAILED, RETRY, RECORD RETRY TIMES.
  127. //TODO:
  128.  
  129. return "ok";
  130. }
  131.  
  132. }
  133. }
  134.  
  135. package com.italktv.platform.audioDist.task;
  136.  
  137. import java.util.Collection;
  138. import java.util.HashMap;
  139. import java.util.Map;
  140. import java.util.concurrent.ExecutionException;
  141. import java.util.concurrent.ExecutorService;
  142. import java.util.concurrent.Executors;
  143. import java.util.concurrent.Future;
  144. import java.util.concurrent.TimeUnit;
  145.  
  146. import javax.annotation.PostConstruct;
  147. import javax.annotation.PreDestroy;
  148.  
  149. import org.slf4j.LoggerFactory;
  150. import org.springframework.stereotype.Component;
  151.  
  152. @Component
  153. public class TaskManager {
  154.  
  155. private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TaskManager.class);
  156.  
  157. // @Resource(lookup = "java:comp/DefaultManagedScheduledExecutorService")
  158. // ManagedScheduledExecutorService executor;
  159.  
  160. Map<String, Future<String>> tasks;
  161. ExecutorService executor ;
  162. @PostConstruct
  163. public void init() {
  164. logger.info(" === init TaskManager===");
  165. tasks = new HashMap<String, Future<String>>();
  166. executor = Executors.newFixedThreadPool(3);
  167. }
  168.  
  169. public void add(MyTask task) {
  170. logger.info("add delay:"+ task.partId+task.srcFile);
  171. Future<String> future = executor.submit(task);
  172. tasks.put(task.srcFile, future);
  173. }
  174.  
  175. public boolean cancel(String name) {
  176. logger.info("cancel "+ name);
  177. boolean ret = false;
  178. Future<String> future = tasks.get(name);
  179. if (future == null) {
  180. logger.info("Not found name:" + name);
  181. } else {
  182. ret = future.cancel(true);
  183. logger.info("cancel "+ name+":"+ret);
  184. tasks.remove(name);
  185. }
  186. return ret;
  187. }
  188.  
  189. public void waitTaskDone(){
  190. Collection<Future<String>> futuretasks = tasks.values();
  191. for(Future<String> future: futuretasks ){
  192. System.out.println("future done? " + future.isDone());
  193.  
  194. String result="";
  195. try {
  196. result = future.get();
  197. } catch (InterruptedException | ExecutionException e) {
  198. logger.error("future exec failed.");
  199. e.printStackTrace();
  200. }
  201.  
  202. System.out.println("future done? " + future.isDone());
  203. System.out.print("result: " + result);
  204. }
  205. }
  206. @PreDestroy
  207. public void destroy(){
  208. try {
  209. System.out.println("attempt to shutdown executor");
  210. executor.shutdown();
  211. executor.awaitTermination(5, TimeUnit.SECONDS);
  212. }
  213. catch (InterruptedException e) {
  214. System.err.println("tasks interrupted");
  215. }
  216. finally {
  217. if (!executor.isTerminated()) {
  218. System.err.println("cancel non-finished tasks");
  219. }
  220. executor.shutdownNow();
  221. System.out.println("shutdown finished");
  222. }
  223. }
  224. }
  225.  
  226. package com.italktv.platform.audioDist.task;
  227.  
  228. import java.util.concurrent.Callable;
  229. import java.util.concurrent.TimeUnit;
  230.  
  231. public abstract class MyTask implements Callable<String> {
  232. protected String srcFile;
  233. protected int partId;
  234. String programId;
  235.  
  236. protected MyTask() {
  237.  
  238. }
  239.  
  240. }

java ee wildfly spring 在线程池的线程中注入的更多相关文章

  1. 由浅入深理解Java线程池及线程池的如何使用

    前言 多线程的异步执行方式,虽然能够最大限度发挥多核计算机的计算能力,但是如果不加控制,反而会对系统造成负担.线程本身也要占用内存空间,大量的线程会占用内存资源并且可能会导致Out of Memory ...

  2. -1-5 java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait(),notify(),notifyAll()等方法都定义在Object类中

     本文关键词: java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁  sleep()和wait()方法的区别 为什么wait( ...

  3. Java多线程、线程池和线程安全整理

    多线程 1.1      多线程介绍 进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程序,并且具有一定独立功能. 1.2      Thread类 通 ...

  4. Java多线程系列 JUC线程池03 线程池原理解析(二)

    转载  http://www.cnblogs.com/skywang12345/p/3509954.html  http://www.cnblogs.com/skywang12345/p/351294 ...

  5. Java多线程系列 JUC线程池02 线程池原理解析(一)

    转载  http://www.cnblogs.com/skywang12345/p/3509960.html ; http://www.cnblogs.com/skywang12345/p/35099 ...

  6. Java多线程系列 JUC线程池01 线程池框架

    转载  http://www.cnblogs.com/skywang12345/p/3509903.html 为什么引入Executor线程池框架 new Thread()的缺点 1. 每次new T ...

  7. java 线程池(线程的复用)

    一. 线程池简介 1. 线程池的概念: 线程池就是首先创建一些线程,它们的集合称为线程池.使用线程池可以很好地提高性能,线程池在系统启动时即创建大量空闲的线程,程序将一个任务传给线程池,线程池就会启动 ...

  8. Java多线程系列 JUC线程池07 线程池原理解析(六)

     关闭“线程池” shutdown()的源码如下: public void shutdown() { final ReentrantLock mainLock = this.mainLock; // ...

  9. 基于线程池的线程管理(BlockingQueue生产者消费者方式)实例

    1.线程池管理类: public class ThreadPoolManager { private static ThreadPoolManager instance = new ThreadPoo ...

随机推荐

  1. [转帖]Windows注册表内容详解

    Windows注册表内容详解 来源:http://blog.sina.com.cn/s/blog_4d41e2690100q33v.html 对 windows注册表一知半解 不是很清晰 这里学习一下 ...

  2. git fetch 更新远程代码到本地仓库

    理解 fetch 的关键, 是理解 FETCH_HEAD,FETCH_HEAD指的是: 某个branch在服务器上的最新状态’.这个列表保存在 .Git/FETCH_HEAD 文件中, 其中每一行对应 ...

  3. 设置SQLServer数据库内存

    需要设置SQLServer数据库的内存配置.登录数据库,这里使用的是SQLServer2008,右键点击最上方的服务器名,在弹出的菜单中,点击属性] 打开服务器属性窗口.默认显示的是第一项[常规]内容 ...

  4. C# Note23: 如何自定义类型使用foreach循环

    前言 在foreach语句代码中,我们经常是对List,Collection,Dictionary等类型的数据进行操作,不过C#允许用户自定义自己的类型来使用foreach语句.那么自定义类型能够使用 ...

  5. Django的模板层

    一 模版简介 你可能已经注意到我们在例子视图中返回文本的方式有点特别. 也就是说,HTML被直接硬编码在 Python代码之中. def current_datetime(request): now ...

  6. RDD特性

  7. python爬虫之MongoDB测试环境安装

    一.   下载 从http://www.mongodb.org/downloads地址中下载:mongodb-linux-x86_64-2.4.11.tar 二.  安装 1>设置mongoDB ...

  8. Jenkins+PowerShell持续集成环境搭建(六)参数化构建

    参数化构建可以应用于动态绑定源码地址等情况. 勾选“This build is parameterized”: 如果需要动态绑定源码地址,参考: 配置完成后构建项目变成:

  9. 搭建Hexo博客(二)-连接github

    没有github账号先需要创建账号,地址:https://github.com/join?source=header 有账号的看下面: 1.创建repo 创建一个repo,名称为yourname.gi ...

  10. linux-shell系列3-wafAPI

    #!/bin/bash datestr=`env LANG=en_US.UTF-8 date -u "+%a, %d %b %Y %H:%M:%S GMT"`pwdstr=`ech ...