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 ...
随机推荐
- [转帖]Windows注册表内容详解
Windows注册表内容详解 来源:http://blog.sina.com.cn/s/blog_4d41e2690100q33v.html 对 windows注册表一知半解 不是很清晰 这里学习一下 ...
- git fetch 更新远程代码到本地仓库
理解 fetch 的关键, 是理解 FETCH_HEAD,FETCH_HEAD指的是: 某个branch在服务器上的最新状态’.这个列表保存在 .Git/FETCH_HEAD 文件中, 其中每一行对应 ...
- 设置SQLServer数据库内存
需要设置SQLServer数据库的内存配置.登录数据库,这里使用的是SQLServer2008,右键点击最上方的服务器名,在弹出的菜单中,点击属性] 打开服务器属性窗口.默认显示的是第一项[常规]内容 ...
- C# Note23: 如何自定义类型使用foreach循环
前言 在foreach语句代码中,我们经常是对List,Collection,Dictionary等类型的数据进行操作,不过C#允许用户自定义自己的类型来使用foreach语句.那么自定义类型能够使用 ...
- Django的模板层
一 模版简介 你可能已经注意到我们在例子视图中返回文本的方式有点特别. 也就是说,HTML被直接硬编码在 Python代码之中. def current_datetime(request): now ...
- RDD特性
- python爬虫之MongoDB测试环境安装
一. 下载 从http://www.mongodb.org/downloads地址中下载:mongodb-linux-x86_64-2.4.11.tar 二. 安装 1>设置mongoDB ...
- Jenkins+PowerShell持续集成环境搭建(六)参数化构建
参数化构建可以应用于动态绑定源码地址等情况. 勾选“This build is parameterized”: 如果需要动态绑定源码地址,参考: 配置完成后构建项目变成:
- 搭建Hexo博客(二)-连接github
没有github账号先需要创建账号,地址:https://github.com/join?source=header 有账号的看下面: 1.创建repo 创建一个repo,名称为yourname.gi ...
- 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 ...