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 ...
随机推荐
- [转帖]xargs命令详解,xargs与管道的区别
xargs命令详解,xargs与管道的区别 https://www.cnblogs.com/wangqiguo/p/6464234.html 之前一直说要学习一下 xargs 到现在为止也没学习.. ...
- 【Java基础】for循环实现在控制台打印水仙花数
代码: /* * 需求:在控制台输出所有的”水仙花数” * * 分析: * 什么是水仙花数呢? * 所谓的水仙花数是指一个三位数,其各位数字的立方和等于该数本身. * 举例:153就是一个水仙花数. ...
- js实现input的赋值
input框赋值如下所示,是一个文本框的html代码,实际开发中,要涉及到将数据库中的数据取出然后放入input框中. <input id="name1" name=&quo ...
- MRP设置自动执行
1.在计划向导中,找到调度运算,如下配置, 2.配置成功后自动生成执行计划
- C# Note18: 使用wpf制作about dialog(关于对话框)
前言 基本上任何software或application都会在help菜单中,有着一个关于对话框,介绍产品的版权.版本等信息,还有就是对第三方的引用(add author credits). 首先,看 ...
- Django进阶知识
drf学习之Django进阶点 一.Django migrations原理 1.makemigrattions: 相当于在每个app下的migrations文件夹下生成一个py脚本文件用于创建表或则修 ...
- python学习笔记(4)-基本数据类型-数字类型及操作
大学mooc 北京理工大学 python语言程序设计课程学习笔记 一.整数类型 可正可负,没有取值范围的限制(这个与c不同,c要考虑数据类型的存储空间).如pow(x,y),计算x的y次方,pow(2 ...
- Centso7 简单优化(阿里云服务器)
##.下载常用包 # yum -y install wget net-tools screen lsof tcpdump nc mtr openssl-devel vim bash-completio ...
- MSDN学习: 加密解密Config文件中的Sections( Encrypting and Decrypting Configuration Sections)
https://msdn.microsoft.com/en-us/library/wfc2t3az(v=vs.100).aspx https://msdn.microsoft.com/en-us/li ...
- P2084 进制转换
原题链接 https://www.luogu.org/problemnew/show/P2084 这个题的思路就是先将输入的数字存到字符数组里,然后求出这一串数字中的非0元素的个数total,并记录最 ...