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 在线程池的线程中注入的更多相关文章

  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. easyUI 数据表格datagrid的使用

    <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title&g ...

  2. ToroiseGit提交代码上传到阿里云的Gitlab

    https://blog.csdn.net/xiaomogg/article/details/51903004(copy) 准备 具体过程 准备 1.拥有一个GitHub账户 2.安装了Tortois ...

  3. CentOS7下Nginx搭建反向代理,并使用redis保存session

    1.启动两个tomcat,端口分别为8080,8081 2.配置nginx,vim /usr/local/nginx/conf/nginx.conf 添加如下配置: 3.启动nginx或热加载 启动: ...

  4. 在windows 7上安装TensorFlow

    TensorFlow是一个开源软件库,用于各种感知和语言理解任务的机器学习.目前被50个团队用于研究和生产许多Google商业产品,如语音识别.Gmail.Google 相册和搜索,其中许多产品曾使用 ...

  5. k8s使用Glusterfs动态生成pv

    一.环境介绍 [root@k8s-m ~]# cat /etc/hosts127.0.0.1 localhost localhost.localdomain localhost4 localhost4 ...

  6. idea -> Error during artifact deployment. See server log for details.

    用idea导入eclipse工程,运行时,报Error during artifact deployment. See server log for details. 谷歌,最后发现是最新  tomc ...

  7. Python——tkinter操作

    一.创建单选框 form tkinter import * #创建窗口体 window = tk() #初始化组合件绑定 w1 = IntVar() #设置初始选择项1 w1.set(1) def O ...

  8. Stream、FileStream、MemoryStream的区别

    1.Stream:流,在msdn的定义:提供字节序列的一般性视图,Stream提供了读写流的方法是以字节的形式从流中读取内容.而我们经常会用到从字节流中读取文本或者写入文本,微软提供了StreamRe ...

  9. LODOP安装参数 及静默安装

    在cmd命令里里静默安装lodop(c-lodop不能静默安装),本人的安装文件放在D:\lodopdownload\3060\Lodop6.224_Clodop3.060,如下所示: lodop静默 ...

  10. Javascript和Jquery语法对比总结

    目的 相信大家都知道jq是js的一个类库,是为了方便我们开发前端,但是笔者在刚开始学习js和jq时经常将两者的语法记混和混用,所以整理下两者实现相同功能之前的语法区别. 声明变量 javascript ...