ssm框架中 ,服务器启动开启线程,线程中使用添加了spring注解类中的方法

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

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

<listener>
	   <listener-class>com.hiteamtech.app.common.TimerUtil</listener-class>
	</listener>

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> 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 {
        @Override  
        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();  
        }  
          
        @Override  
        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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值