package com.yihu.wlyy.redis; import com.alibaba.fastjson.JSONObject; import com.yihu.wlyy.service.app.prescription.PrescriptionService; import com.yihu.wlyy.task.PushMsgTask; import com.yihu.wlyy.util.SystemConf; import org.apache.commons.lang3.StringUtils; 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.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * Created by Trick on 2017/8/7. */ @Component public class RedisThread implements Runnable { private static Logger logger = LoggerFactory.getLogger(RedisThread.class); @Value("${channel.redis.host}") private String host; @Value("${channel.redis.port}") private Integer port; @Value("${channel.redis.password}") private String password; @Autowired private StringRedisTemplate redisTemplate; @Autowired private PrescriptionService prescriptionService; @Autowired private PushMsgTask pushMsgTask; //redis链接池 private JedisPool pool; @Override public void run() { String key = SystemConf.getInstance().getSystemProperties().getProperty("redis_prescription_title"); //初始化链接池 initPool(); while (true){ try { Jedis jedis = pool.getResource(); String message = jedis.rpop(key); if(StringUtils.isEmpty(message)){ sleep(1000L);//如果没有读取到记录,等待1秒 }else { redisMessage(message); } }catch (Exception e){ logger.info(e.getMessage()); sleep(5000L); initPool(); } } } public void sleep(Long time){ try { Thread.sleep(time); }catch (Exception e){ logger.error(e.getMessage()); } } public void initPool(){ JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxIdle(8); poolConfig.setMaxTotal(8); poolConfig.setMaxWaitMillis(-1); poolConfig.setMinIdle(1); if(StringUtils.isNotBlank(password)){ pool = new JedisPool(poolConfig,host,port,100000,password); }else { pool = new JedisPool(poolConfig,host,port,100000); } } public void redisMessage(String message){ logger.info("redis_onMessage...:"+message); //this.unsubscribe(); try{ JSONObject json = JSONObject.parseObject(message); String title = json.getString("title"); if("dispensingComplete".equals(title)){//配药完成 //药品配送完成,提醒取药 String prescriptionCode = json.getString("prescription"); prescriptionService.dispensingComplete(prescriptionCode); }else if("wechat".equals(title)){ String data = json.getString("value"); pushMsgTask.getQueue().put(new org.json.JSONObject(data)); }else{ } }catch (Exception e){ logger.error("redis_error...",e); } } }