博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
ssm框架中 ,服务器启动开启线程,线程中使用添加了spring注解类中的方法
阅读量:6255 次
发布时间:2019-06-22

本文共 4602 字,大约阅读时间需要 15 分钟。

hot3.png

——ssm框架中服务器一启动开启一条线程

1.使用监听器,在web.xml中进行配置

com.hiteamtech.app.common.TimerUtil

2。获取bean的工具类

import java.util.Locale;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;/**  * 项目名称:  * 类名: SpringContextUtil * 描述: 获取bean的工具类,可用于在线程里面获取bean */public class SpringContextUtil implements ApplicationContextAware {    private static ApplicationContext context = null;    /* (non Javadoc)     * @Title: setApplicationContext     * @Description: spring获取bean工具类     * @param applicationContext     * @throws BeansException     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)     */    @Override    public void setApplicationContext(ApplicationContext applicationContext)            throws BeansException {        this.context = applicationContext;    }    public static 
T getBean(String beanName){ return (T) context.getBean(beanName); } public static String getMessage(String key){ return context.getMessage(key, null, Locale.getDefault()); }}

3.在applicationContext.xml配置文件中注入这个工具类

<bean id="springContextUtil" class="com.hiteamtech.app.common.SpringContextUtil"></bean>

4.TimerUtils.java文件

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration({ "classpath:sqlMapConfig.xml","classpath:springmvc.xml","classpath:applicationContext.xml","classpath:captcha-context.xml" })
public class TimerUtil implements ServletContextListener {
         
        public void contextInitialized(ServletContextEvent arg0) {  
            // run in a second  使用工具类获取使用了@service注解的SettingsServiceImpl对象
            ISettingsService settingsService = SpringContextUtil.getBean("settingsServiceImpl");;
            final long timeInterval = 1000*60;  
            Runnable runnable = new Runnable() {  
                public void run() {  
                    while (true) {  
                        long l = System.currentTimeMillis();
                        Date date = new Date(l);
                        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
                        System.out.println(dateFormat.format(date));
                        settingsService.updateRemindTimeBySid("18b138ded96546179149e6bf502485c4");
                        try {  
                            Thread.sleep(timeInterval);  
                        } catch (InterruptedException e) {  
                            e.printStackTrace();  
                        }  
                    }  
                }  
            };  
            Thread thread = new Thread(runnable);  
            thread.start();  
        }  
          
         
        public void contextDestroyed(ServletContextEvent arg0) {  
            // TODO Auto-generated method stub  
              
        }        
}

二.接口访问时开启线程

线程类:

public class RobotThread extends Thread {	/**日志记录器*/	Logger log = Logger.getLogger(RobotThread.class);	//要添加的机器人个数	private String[] robots;	//线程动作指令  addRobot添加机器人,delRobot删除机器人	private String cmd = null;	//直播间id	private String liveId = null;		private ILiveCacheService liveCache;		private IUserCacheService userCache;		private IRyIMService imService;		public RobotThread(ILiveCacheService liveCache,IUserCacheService userCache,IRyIMService imService, String liveId, String[] robots, String cmd){		this.liveCache = liveCache;		this.robots = robots;		this.cmd = cmd;		this.liveId = liveId;		this.userCache = userCache;		this.imService = imService;	}		/**	 * 异步销毁直播缓存数据	 */	public void run() {		log.debug(" cmd:"+this.cmd);		switch (cmd) {		case "addRobot":			this.updateRobot();			break;		case "delRobot":			this.updateRobot();			break;		default:			//错误处理机制			break;		}	}			private void updateRobot(){		}			public static void main(String[] args) {		Random rd = new Random();		for (int i = 0; i < 100; i++) {			System.out.println(rd.nextInt(10)+2);			/*try {				//随机休眠1,2秒添加一个				Thread.sleep(1000*(rd.nextInt(6)+2));			} catch (InterruptedException e1) {				e1.printStackTrace();			}*/		}	}	}

调用线程的controller:

@Controller@RequestMapping("/liveNotify")public class LiveNotifyController extends BaseController {	/**日志记录器*/	Logger log = Logger.getLogger(LiveNotifyController.class);		@Autowired	private ILiveService liveService;		@Autowired	private LiveCacheService liveCache;		@Autowired	private IUserCacheService userCache;		@Autowired	private IRyIMService IMService;		@Autowired	private UserFansMapper userFansDAO;		@Autowired	private IUserCacheService cacheService;		@Autowired	private IRyIMService imService;		@Resource	private UserBlackListMapper userBlackListDao;		@Resource	private UserFansMapper userFansDao;		@Resource	private UserInfoMapper userInfoDao;	@RequestMapping(value = "/liveRobot", method = RequestMethod.POST)	public void liveJqg(HttpServletRequest req, HttpServletResponse resp){		//启用异步线程,添加机器人		new RobotThread(liveCache, userCache, IMService, liveId, robots, cmd).start();		super.outMsg(200, "success", resp);	}

方法仅供参考。

转载于:https://my.oschina.net/u/660595/blog/884552

你可能感兴趣的文章
【转】C++标准转换运算符const_cast
查看>>
ssh密码
查看>>
常用的HTML富文本编译器UEditor、CKEditor、TinyMCE、HTMLArea、eWebEditor、KindEditor简介...
查看>>
【Saltstack】Saltstack简单说明
查看>>
[转]香农信息论与毒药称球问题
查看>>
HTTP Error 500.19
查看>>
我在博客园的这一年
查看>>
红黑树
查看>>
Jackson使用ObjectManage#readValue传入泛型T的问题
查看>>
Python正则表达式中的re.S的作用
查看>>
从零开始构建一个centos+jdk7+tomcat7的docker镜像文件
查看>>
Source Insight 中文注释为乱码解决办法(完美解决,一键搞定)
查看>>
【LoadRunner】安装LoadRunner
查看>>
Linux内存管理 (15)页面迁移
查看>>
在高并发、高负载的情况下,如何给表添加字段并设置DEFAULT值?
查看>>
Cocos2d-x 3.0final 终结者系列教程13-贪食蛇游戏案例(全)
查看>>
Nginx的try_files指令和命名location使用实例
查看>>
IO多路复用之select
查看>>
pd_ds中的hash
查看>>
买书不读是一种什么病?
查看>>