java ee wildfly spring 在线程池的线程中注入
public class RtmpSpyingTests extends AbstractTransactionalJUnit4SpringContextTests {
@Autowired
ThreadPoolTaskExecutor rtmpSpyingTaskExecutor; @Autowired
ApplicationContext ctx; @Autowired
RtmpSourceRepository rtmpRep; @Test
public void test() {
RtmpSource rtmpSourceSample = new RtmpSource("test"); rtmpRep.save(rtmpSourceSample);
rtmpRep.flush(); List<RtmpSource> rtmpSourceList = rtmpRep.findAll(); // Here I get a list containing rtmpSourceSample RtmpSpyingTask rtmpSpyingTask = ctx.getBean(RtmpSpyingTask.class,
"arg1","arg2");
rtmpSpyingTaskExecutor.execute(rtmpSpyingTask); }
} public class RtmpSpyingTask implements Runnable { @Autowired
RtmpSourceRepository rtmpRep; String nameIdCh;
String rtmpUrl; public RtmpSpyingTask(String nameIdCh, String rtmpUrl) {
this.nameIdCh = nameIdCh;
this.rtmpUrl = rtmpUrl;
} public void run() {
// Here I should get a list containing rtmpSourceSample, but instead of that
// I get an empty list
List<RtmpSource> rtmpSource = rtmpRep.findAll();
}
} 应该用
@Service
public class AsyncTransactionService { @Autowired
RtmpSourceRepository rtmpRep; @Transactional(readOnly = true)
public List<RtmpSource> getRtmpSources() {
return rtmpRep.findAll();
} @Transactional(propagation = Propagation.REQUIRES_NEW)
public void insertRtmpSource(RtmpSource rtmpSource) {
rtmpRep.save(rtmpSource);
}
}
或者
用内部类。
package com.italktv.platform.audioDist.service; import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.concurrent.TimeUnit; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import com.italktv.platform.audioDist.mongo.CustomerRepository;
import com.italktv.platform.audioDist.mongo.PlayUrl;
import com.italktv.platform.audioDist.mongo.PlayUrl.MyUrl;
import com.italktv.platform.audioDist.mongo.PlayUrlRepository;
import com.italktv.platform.audioDist.mysql.SubSet;
import com.italktv.platform.audioDist.mysql.UserRepository;
import com.italktv.platform.audioDist.task.MyTask;
import com.italktv.platform.audioDist.task.TaskManager; @Component
public class ScheduleJobs {
private static final Logger log = LoggerFactory.getLogger(ScheduleJobs.class); public final static long SECOND = 1 * 1000;
LocalDateTime nowDate = LocalDateTime.now(); @Autowired
// This means to get the bean called userRepository
// Which is auto-generated by Spring, we will use it to handle the data
private UserRepository userRepository; @Autowired
private PlayUrlRepository repository;
@Autowired
private CustomerRepository cc; @Autowired
private UserRepository user; @Autowired
TaskManager taskManager; @Scheduled(fixedRate = SECOND * 400)
public void fixedRateJob() {
nowDate = LocalDateTime.now();
System.out.println("=== start distribution: " + nowDate);
dotask();
} // @PostConstruct
// public void init() {
//
// taskManager = new TaskManager();
// taskManager.init();
// }
//
// @PreDestroy
// void destroy() {
// taskManager.destroy();
// } void dotask() { Map<Integer, List<SubSet>> map = userRepository.getUploadFileMap();
for (Entry<Integer, List<SubSet>> subject : map.entrySet()) {
int subjectId = subject.getKey();
log.info(" subject id:" + subjectId);
List<SubSet> allsub = subject.getValue();
for (SubSet item : allsub) {
log.info(" sub:" + item.toString());
taskManager.add(new MessagePublish(item.id, item.path));
} //wait them finished
//TODO: //update subject status
//TODO } } ////////////////////////内部类////////////////////////
public class MessagePublish extends MyTask implements Serializable{
public MessagePublish() {
super();
}
public MessagePublish(int id,String name ){
this.srcFile = name;
this.partId=id;
} @Value("${platform.audio.dist.domain}") private String domain; @Override
public String call() {
System.out.println(srcFile + " is uploading...");
try {
//获取消息发布的区域
TimeUnit.SECONDS.sleep(new Random().nextInt(10)+1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(srcFile + " uploaded."); //2.RECORD TO MONGO DB
PlayUrl play=new PlayUrl();
play.programid="programid fake"+ "";
play.domain=domain;
play.protocol="HTTP";
MyUrl myurl=new MyUrl();
myurl.high="http://xxx.xxx/xi//";
play.url=myurl;
repository.save(play);
//TODO: //IF FAILED, RETRY, RECORD RETRY TIMES.
//TODO: return "ok";
} }
} package com.italktv.platform.audioDist.task; import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; @Component
public class TaskManager { private static final org.slf4j.Logger logger = LoggerFactory.getLogger(TaskManager.class); // @Resource(lookup = "java:comp/DefaultManagedScheduledExecutorService")
// ManagedScheduledExecutorService executor; Map<String, Future<String>> tasks;
ExecutorService executor ;
@PostConstruct
public void init() {
logger.info(" === init TaskManager===");
tasks = new HashMap<String, Future<String>>();
executor = Executors.newFixedThreadPool(3);
} public void add(MyTask task) {
logger.info("add delay:"+ task.partId+task.srcFile);
Future<String> future = executor.submit(task);
tasks.put(task.srcFile, future);
} public boolean cancel(String name) {
logger.info("cancel "+ name);
boolean ret = false;
Future<String> future = tasks.get(name);
if (future == null) {
logger.info("Not found name:" + name);
} else {
ret = future.cancel(true);
logger.info("cancel "+ name+":"+ret);
tasks.remove(name);
}
return ret;
} public void waitTaskDone(){
Collection<Future<String>> futuretasks = tasks.values();
for(Future<String> future: futuretasks ){
System.out.println("future done? " + future.isDone()); String result="";
try {
result = future.get();
} catch (InterruptedException | ExecutionException e) {
logger.error("future exec failed.");
e.printStackTrace();
} System.out.println("future done? " + future.isDone());
System.out.print("result: " + result);
}
}
@PreDestroy
public void destroy(){
try {
System.out.println("attempt to shutdown executor");
executor.shutdown();
executor.awaitTermination(5, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
System.err.println("tasks interrupted");
}
finally {
if (!executor.isTerminated()) {
System.err.println("cancel non-finished tasks");
}
executor.shutdownNow();
System.out.println("shutdown finished");
}
}
} package com.italktv.platform.audioDist.task; import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit; public abstract class MyTask implements Callable<String> {
protected String srcFile;
protected int partId;
String programId; protected MyTask() { } }
java ee wildfly spring 在线程池的线程中注入的更多相关文章
- 由浅入深理解Java线程池及线程池的如何使用
前言 多线程的异步执行方式,虽然能够最大限度发挥多核计算机的计算能力,但是如果不加控制,反而会对系统造成负担.线程本身也要占用内存空间,大量的线程会占用内存资源并且可能会导致Out of Memory ...
- -1-5 java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait(),notify(),notifyAll()等方法都定义在Object类中
本文关键词: java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait( ...
- Java多线程、线程池和线程安全整理
多线程 1.1 多线程介绍 进程指正在运行的程序.确切的来说,当一个程序进入内存运行,即变成一个进程,进程是处于运行过程中的程序,并且具有一定独立功能. 1.2 Thread类 通 ...
- Java多线程系列 JUC线程池03 线程池原理解析(二)
转载 http://www.cnblogs.com/skywang12345/p/3509954.html http://www.cnblogs.com/skywang12345/p/351294 ...
- Java多线程系列 JUC线程池02 线程池原理解析(一)
转载 http://www.cnblogs.com/skywang12345/p/3509960.html ; http://www.cnblogs.com/skywang12345/p/35099 ...
- Java多线程系列 JUC线程池01 线程池框架
转载 http://www.cnblogs.com/skywang12345/p/3509903.html 为什么引入Executor线程池框架 new Thread()的缺点 1. 每次new T ...
- java 线程池(线程的复用)
一. 线程池简介 1. 线程池的概念: 线程池就是首先创建一些线程,它们的集合称为线程池.使用线程池可以很好地提高性能,线程池在系统启动时即创建大量空闲的线程,程序将一个任务传给线程池,线程池就会启动 ...
- Java多线程系列 JUC线程池07 线程池原理解析(六)
关闭“线程池” shutdown()的源码如下: public void shutdown() { final ReentrantLock mainLock = this.mainLock; // ...
- 基于线程池的线程管理(BlockingQueue生产者消费者方式)实例
1.线程池管理类: public class ThreadPoolManager { private static ThreadPoolManager instance = new ThreadPoo ...
随机推荐
- Laravel 5.2+ 使用url()全局函数返回前一个页面的地址
注意:文章标题中5.2+表示该文章内容可向上兼容,适用于Laravel版本5.2及更高(目前最新为5.6),但不可向下兼容,即不适用于5.2版本以下.推荐大家花一点点时间,将自己的Laravel更新至 ...
- node 模块化思想中index.js的重要性
目录结构如上图 module1和modlue2.main在同一级 module1下文件: index.js var test2=require('./test2'); var sayHi=functi ...
- IWMS后台上传文章,嵌入音频文件代码
<object width="260" height="69" classid="clsid:6bf52a52-394a-11d3-b153-0 ...
- QTP自动化测试-笔记 注释、大小写
1 rem 注释内容 2 ' 注释内容 3 快捷键注释-选择代码行-ctrl+M 4 ctrl+shift+同- 取消注释 大小写 qtp:对小写敏感:如果 变量.sheet页是用小写字母命名,则使用 ...
- Directory of X:\EFI\Microsoft\Boot
Directory of X:\EFI\Microsoft\Boot 2017/06/21 15:14 <DIR> . 2017/06/21 15:14 <DIR> .. 20 ...
- 10.Service资源发现
Kubernetes Pods是不可控的.每当一个pod停止后,他不是重启,而是重建.ReplicaSets特别是Pods动态地创建和销毁(例如,当向外扩展或向内扩展时).虽然每个PodIP地址都有自 ...
- Data Science With R In Visual Studio
R Projects Similar to Python, when we installed the data science tools we get an “R” section in our ...
- 学习Linux系统的态度及技巧
Linux作为一种简单快捷的操作系统,现在被广泛的应用.也适合越来越多的计算机爱好者学习和使用.但是对于Linux很多人可能认为很难,觉得它很神秘,从而对其避而远之,但事实真的是这样么?linux真的 ...
- JSON笔记
JSPN示例1: { "firstName": "Brett", "lastName":"McLaughlin", &q ...
- Python多进程、多线程、协程
转载:https://www.cnblogs.com/huangguifeng/p/7632799.html 首先我们来了解下python中的进程,线程以及协程! 从计算机硬件角度: 计算机的核心是C ...