DelayQueue、Redis结合使延迟、定时任务使用

  • 1、延迟任务实体类,需要实现delay,需要redis存储,可以序列化下;
package com.wqq;
import java.io.Serializable;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

/**
 *任务调度系统
 *队列中要执行的任务
 * @author wangqiqi
 * @Date 2018年05月23日
 */
public class Task<T> implements Delayed,Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    /**
     * 到期时间
     */
    private final long time;

    /**
     * 问题对象
     */
    private final T task;
    private static final AtomicLong atomic = new AtomicLong(0);

    private final long n;

    public Task(long timeout, T t) {
        this.time = System.nanoTime() + timeout;
        this.task = t;
        this.n = atomic.getAndIncrement();
    }

    /**
     * 返回与此对象相关的剩余延迟时间,以给定的时间单位表示
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.time - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        // TODO Auto-generated method stub
        if (other == this) // compare zero ONLY if same object
            return 0;
        if (other instanceof Task) {
            Task x = (Task) other;
            long diff = time - x.time;
            if (diff < 0)
                return -1;
            else if (diff > 0)
                return 1;
            else if (n < x.n)
                return -1;
            else
                return 1;
        }
        long d = (getDelay(TimeUnit.NANOSECONDS) - other.getDelay(TimeUnit.NANOSECONDS));
        return (d == 0) ? 0 : ((d < 0) ? -1 : 1);
    }

    public T getTask() {
        return this.task;
    }

    @Override
    public int hashCode() {
        return task.hashCode();
    }

    @Override
    public boolean equals(Object object) {
        if (object instanceof Task) {
            return object.hashCode() == hashCode() ? true : false;
        }
        return false;
    }


}
  • 2、队列定义,消费者、生产者代码;
package com.wqq;

import org.apache.log4j.Logger;

import com.JedisUtils;
import com.wqq.TaskDelay.ApplicationTask;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *任务调度系统
 *后台守护线程不断的执行检测工作
 * @author wangqiqi
 * @Date 2018年05月27日
 */
public class TaskQueueDaemonThread {

    //日志打印
    //private static final Logger LOG = Logger.getLogger(TaskQueueDaemonThread.class);

    private TaskQueueDaemonThread() {
    }

    private static class LazyHolder {
        private static TaskQueueDaemonThread taskQueueDaemonThread = new TaskQueueDaemonThread();
    }

    public static TaskQueueDaemonThread getInstance() {
        return LazyHolder.taskQueueDaemonThread;
    }

    Executor executor = Executors.newFixedThreadPool(20);

    /**
     * 缓存任务
     */
    private ApplicationTask jedis=new ApplicationTask(){
        public void execute() {
            JedisUtils.init(false);
        }
    };
    /**
     * 缓存任务1StudentTask
     */
    private ApplicationTask surveyTask=new ApplicationTask(){
        public void execute() {
            //初始化任务对象
            Student s=new Student();
            //设置任务名称,从缓存中去相应的任务
            s.setTaskName("sms");
            getDelayMap(s);
        }
    };

    /**
     * 管理任务
     */
    public void manage(){
        TaskDelay.getInstance()
        .addTask(jedis)
        .addTask(surveyTask);
    }
    /**
     * 缓存任务2
     */
    /**
     * 守护线程
     */
    private Thread daemonThread;

    /**
     * 初始化守护线程以及任务
     */
    public void init() {
        daemonThread = new Thread(() -> execute());
        /*daemonThread.setDaemon(true);
        daemonThread.setName("Task Queue Daemon Thread");*/
        daemonThread.start();
        manage();
        TaskDelay.getInstance().startTask();
    }

    private void execute() {
        System.out.println("start:" + System.currentTimeMillis());
        while (true) {
            try {
                //从延迟队列中取值,如果没有对象过期则队列一直等待,
                Task t1 = t.take();
                if (t1 != null) {
                    //修改问题的状态
                    Object task = t1.getTask();
                    System.out.println(task);

                    if (task == null) {
                        continue;
                    }
                    delDelayTask(task);
                    //executor.execute(task);//不涉及线程池不适用
                    //LOG.info("[at task:" + task + "]   [Time:" + System.currentTimeMillis() + "]");
                }
            } catch (Exception e) {
                e.printStackTrace();
                break;
            }
        }
    }

    /**
     * 创建一个最初为空的新 DelayQueue,内存的可见性
     */
    private volatile DelayQueue> t = new DelayQueue<>();

    /**
     * Object规定属性1、delayTime(延迟时间)2、taskName(多个延迟任务名字必须唯一)3、自增唯一id
     * 添加任务,
     * time 延迟时间,ms
     * task 任务
     * 用户为问题设置延迟时间
     */
    public void put(long time, Object task) {
        //转换成ns
        long nanoTime = TimeUnit.NANOSECONDS.convert(time, TimeUnit.MILLISECONDS);
        //创建一个任务
        Task k = new Task<>(nanoTime, task);
        //将任务放在延迟的队列中
        t.put(k);

        addDelayTask(task);
    }
    /**
     * 获取延迟任务Map
     * @param task
     * @param id
     */
    public void getDelayMap(Object task){
        if(JedisUtils.exists(getDelayTaskName(task))){
            Map map=JedisUtils.getObjectMap(getDelayTaskName(task));
            long delayTime;
            long addTimeMillis;
            long nowTimeMillis;
            for(String s:map.keySet()){
                delayTime = Long.parseLong(getDelayTime(map.get(s)));
                addTimeMillis = Long.parseLong(getDelayAddTimeMillis(map.get(s)));
                nowTimeMillis = System.currentTimeMillis();
                delayTime=delayTime+addTimeMillis-nowTimeMillis;
                if(delayTime<0){
                    delayTime=0;
                }
                TaskQueueDaemonThread.getInstance().put(delayTime,map.get(s));
            }
        }
    }
    /**
     * 延迟任务add
     * @param task
     * @param id
     */
    public void addDelayTask(Object task) {
        Map  map=new HashMap<>();
        map.put(getDelayId(task), task);
        if(JedisUtils.exists(getDelayTaskName(task))){
            JedisUtils.mapObjectPut(getDelayTaskName(task), map);
        }else{
            JedisUtils.setObjectMap(getDelayTaskName(task),map,0);
        }   
    }
    /**
     * 延迟任务del
     * @param task
     * @param id
     */
    public long delDelayTask(Object task) {
        long result = 0;
        if(JedisUtils.mapExists(getDelayTaskName(task),getDelayId(task))){
            result = JedisUtils.mapRemove(getDelayTaskName(task),getDelayId(task));
        }
        return result;
    }

    /**
     * @param task
     */
    public boolean endTask(Task task){
        return t.remove(task);
    }
    /**
     * 延迟id
     * @param task
     * @return
     */
    public String getDelayId(Object task) {
        return getFieldValueByName("id", task).toString();
    }
    /**
     * 延迟任务名称
     * @param task
     * @return
     */
    public String getDelayTaskName(Object task) {
        return getFieldValueByName("taskName", task).toString();
    }
    /**
     * 延迟时间
     * @param task
     * @return
     */
    public String getDelayTime(Object task) {
        return getFieldValueByName("delayTime", task).toString();
    }
    /**
     * 延迟时间
     * @param task
     * @return
     */
    public String getDelayAddTimeMillis(Object task) {
        return getFieldValueByName("addTimeMillis", task).toString();
    }
    /** 
     * 根据属性名获取属性值 
     * */  
    public Object getFieldValueByName(String fieldName, Object o) {  
        try {    
            String firstLetter = fieldName.substring(0, 1).toUpperCase();    
            String getter = "get" + firstLetter + fieldName.substring(1);    
            Method method = o.getClass().getMethod(getter, new Class[] {});    
            Object value = method.invoke(o, new Object[] {});    
            return value;    
        } catch (Exception e) {    
            return null;    
        }    
    }
}
  • 3、任务机;
package com.wqq;

import java.util.ArrayList;
import java.util.List;

/**
 * 延迟任务机
 * @author wangqiqi
 * @Date 2018年05月23日
 */
public class TaskDelay {
    /** 实例 */
    private static final TaskDelay INSTANCE = new TaskDelay();
    /** 任务机所有的任务 */
    private volatile static List TASKS = new ArrayList();
    /**
     * 私有构造方法
     */
    private TaskDelay() {

    }
    /**
     * 获取实例
     * @return {@link TaskMachine}
     */
    public static TaskDelay getInstance() {
        return INSTANCE;
    }
    /**
     * 添加任务
     * @param task {@link ApplicationTask}
     */
    public TaskDelay addTask(ApplicationTask task) {
        if (TASKS.indexOf(task) == -1) {
            TASKS.add(task);
        }
        return INSTANCE;
    }
    /**
     * 执行任务
     * @param task {@link ApplicationTask}
     */
    public void startTask() {
        for (ApplicationTask task : TASKS) {
            if (task == null) {
                continue;
            }
            task.execute();
        }
    }

    /**
     * 应用任务
     */
    public static interface ApplicationTask {
        /**
         * 任务执行
         */
        void execute();
    } 
}
  • 4、任务对象;
package com.wqq;

import java.io.Serializable;

public class Student implements Serializable {
    /**
     * 序列化
     */
    private static final long serialVersionUID = 1L;
    /**延迟任务属性start()必须序列化*/
    /**自增id主键*/
    private Long id;
    /**延迟时间*/
    private String delayTime;
    /**延迟任务名称,项目延迟任务唯一*/
    private String taskName;
    /**添加任务时间毫秒值*/
    private Long addTimeMillis;
    /**延迟任务属性end*/

    private String name;
    @Override
    public String toString() {
        return "Student [id=" + id + ", delayTime=" + delayTime + ", taskName=" + taskName + ", addTimeMillis="
                + addTimeMillis + ", name=" + name + "]";
    }
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDelayTime() {
        return delayTime;
    }

    public void setDelayTime(String delayTime) {
        this.delayTime = delayTime;
    }

    public String getTaskName() {
        return taskName;
    }

    public void setTaskName(String taskName) {
        this.taskName = taskName;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getAddTimeMillis() {
        return addTimeMillis;
    }

    public void setAddTimeMillis(Long addTimeMillis) {
        this.addTimeMillis = addTimeMillis;
    }



}
  • 5、redis缓存任务对象;
package com;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisException;

/**
 * Jedis Cache 工具类
 * 
 * @author wangqiqi
 * @Date 2018年05月23日
 */
public class JedisUtils {
    private static final Logger logger = Logger.getLogger(JedisUtils.class);
    private static JedisPool jedisPool = null;
    private static final String CHARSET_NAME = "UTF-8";
    /** 
     * 初始化redis连接池 
     */  
    public static void init(boolean falg) {  
        JedisPoolConfig config = new JedisPoolConfig(); // Jedis连接池  
        config.setMaxIdle(8); // 最大空闲连接数  
        config.setMaxTotal(8);// 最大连接数  
        config.setMaxWaitMillis(1000); // 获取连接是的最大等待时间,如果超时就抛出异常  
        config.setTestOnBorrow(false);// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;  
        config.setTestOnReturn(true);  
        //jedisPool = new JedisPool(config, "127.0.0.1", 6379, 5000, "123456", 0); // 配置、ip、端口、连接超时时间、密码、数据库编号(0~15)  
        jedisPool = new JedisPool(config, "127.0.0.1", 6379, 5000);
        System.out.println("Connection to server sucessfully");
        Jedis jedis = jedisPool.getResource(); 
        System.out.println("Server is running: " + jedis.ping());
        if(falg==true){
            jedis.flushDB();
        }
    }
    public static void main(String[] args) {
        init(true);
    }
    /**
     * 获取缓存
     * @param key 键
     * @return 值
     */
    public static String get(String key) {
        String value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                value = jedis.get(key);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取缓存
     * @param key 键
     * @return 值
     */
    public static Object getObject(String key) {
        Object value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(getBytesKey(key))) {
                value = toObject(jedis.get(getBytesKey(key)));
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 设置缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static String set(String key, String value, int cacheSeconds) {
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.set(key, value);
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 设置缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static String setObject(String key, Object value, int cacheSeconds) {
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.set(getBytesKey(key), toBytes(value));
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 获取List缓存
     * @param key 键
     * @return 值
     */
    public static List getList(String key) {
        List value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                value = jedis.lrange(key, 0, -1);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取List缓存
     * @param key 键
     * @return 值
     */
    public static List getObjectList(String key) {
        List value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(getBytesKey(key))) {
                List<byte[]> list = jedis.lrange(getBytesKey(key), 0, -1);
                value =new ArrayList<>();
                for (byte[] bs : list){
                    value.add(toObject(bs));
                }
            }
        } catch (Exception e) {

        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 设置List缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static long setList(String key, List value, int cacheSeconds) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                jedis.del(key);
            }
            result = jedis.rpush(key, (String[])value.toArray());
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 设置List缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static long setObjectList(String key, List value, int cacheSeconds) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(getBytesKey(key))) {
                jedis.del(key);
            }
            List<byte[]> list = new ArrayList<>();
            for (Object o : value){
                list.add(toBytes(o));
            }
            result = jedis.rpush(getBytesKey(key), (byte[][])list.toArray());
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 向List缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static long listAdd(String key, String... value) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.rpush(key, value);
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 向List缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static long listObjectAdd(String key, Object... value) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            List<byte[]> list = new ArrayList<>();
            for (Object o : value){
                list.add(toBytes(o));
            }
            result = jedis.rpush(getBytesKey(key), (byte[][])list.toArray());
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 获取缓存
     * @param key 键
     * @return 值
     */
    public static Set getSet(String key) {
        Set value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                value = jedis.smembers(key);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取缓存
     * @param key 键
     * @return 值
     */
    public static Set getObjectSet(String key) {
        Set value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(getBytesKey(key))) {
                value = new HashSet<>();
                Set<byte[]> set = jedis.smembers(getBytesKey(key));
                for (byte[] bs : set){
                    value.add(toObject(bs));
                }
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 设置Set缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static long setSet(String key, Set value, int cacheSeconds) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                jedis.del(key);
            }
            result = jedis.sadd(key, (String[])value.toArray());
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 设置Set缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static long setObjectSet(String key, Set value, int cacheSeconds) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(getBytesKey(key))) {
                jedis.del(key);
            }
            Set<byte[]> set =new HashSet<>();
            for (Object o : value){
                set.add(toBytes(o));
            }
            result = jedis.sadd(getBytesKey(key), (byte[][])set.toArray());
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 向Set缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static long setSetAdd(String key, String... value) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.sadd(key, value);
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 向Set缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static long setSetObjectAdd(String key, Object... value) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            Set<byte[]> set =new HashSet<>();
            for (Object o : value){
                set.add(toBytes(o));
            }
            result = jedis.rpush(getBytesKey(key), (byte[][])set.toArray());
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 获取Map缓存
     * @param key 键
     * @return 值
     */
    public static Map getMap(String key) {
        Map value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                value = jedis.hgetAll(key);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取Map缓存
     * @param key 键
     * @return 值
     */
    public static Map getObjectMap(String key) {
        Map value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(getBytesKey(key))) {
                value =new HashMap<>();
                Map<byte[], byte[]> map = jedis.hgetAll(getBytesKey(key));
                for (Map.Entry<byte[], byte[]> e : map.entrySet()){
                    value.put(new String(e.getKey(),"UTF-8"), toObject(e.getValue()));
                }
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 设置Map缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static String setMap(String key, Map value, int cacheSeconds) {
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                jedis.del(key);
            }
            result = jedis.hmset(key, value);
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 设置Map缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static String setObjectMap(String key, Map value, int cacheSeconds) {
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(getBytesKey(key))) {
                jedis.del(key);
            }
            Map<byte[], byte[]> map =new HashMap<>();
            for (Map.Entry e : value.entrySet()){
                map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
            }
            result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>)map);
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 向Map缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static String mapPut(String key, Map value) {
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.hmset(key, value);
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 向Map缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static String mapObjectPut(String key, Map value) {
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            Map<byte[], byte[]> map = new HashMap<>();
            for (Map.Entry e : value.entrySet()){
                map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
            }
            result = jedis.hmset(getBytesKey(key), (Map<byte[], byte[]>)map);
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }
    /**
     * 移除Map缓存中的值
     * @param key 键
     * @param value 值
     * @return
     */
    public static long mapRemove(String key, String mapKey) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.hdel(key, mapKey);
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 移除Map缓存中的值
     * @param key 键
     * @param value 值
     * @return
     */
    public static long mapObjectRemove(String key, String mapKey) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.hdel(getBytesKey(key), getBytesKey(mapKey));
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 判断Map缓存中的Key是否存在
     * @param key 键
     * @param value 值
     * @return
     */
    public static boolean mapExists(String key, String mapKey) {
        boolean result = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.hexists(key, mapKey);
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 判断Map缓存中的Key是否存在
     * @param key 键
     * @param value 值
     * @return
     */
    public static boolean mapObjectExists(String key, String mapKey) {
        boolean result = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.hexists(getBytesKey(key), getBytesKey(mapKey));
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 删除缓存
     * @param key 键
     * @return
     */
    public static long del(String key) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)){
                result = jedis.del(key);
            }else{
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 删除缓存
     * @param key 键
     * @return
     */
    public static long delObject(String key) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(getBytesKey(key))){
                result = jedis.del(getBytesKey(key));
            }else{
            }
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 缓存是否存在
     * @param key 键
     * @return
     */
    public static boolean exists(String key) {
        boolean result = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.exists(key);
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 缓存是否存在
     * @param key 键
     * @return
     */
    public static boolean existsObject(String key) {
        boolean result = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.exists(getBytesKey(key));
        } catch (Exception e) {
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 获取资源
     * @return
     * @throws JedisException
     */
    public static Jedis getResource() throws JedisException {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
//          logger.debug("getResource.", jedis);
        } catch (JedisException e) {
            returnBrokenResource(jedis);
            throw e;
        }
        return jedis;
    }

    /**
     * 归还资源
     * @param jedis
     * @param isBroken
     */
    public static void returnBrokenResource(Jedis jedis) {
        if (jedis != null) {
            //jedisPool.returnBrokenResource(jedis);
            jedis.close();
        }
    }
    /**
     * 释放资源
     * @param jedis
     * @param isBroken
     */
    public static void returnResource(Jedis jedis) {
        if (jedis != null) {
            //jedisPool.returnResource(jedis);
            jedis.close();
        }
    }

    /**
     * 获取byte[]类型Key
     * @param key
     * @return
     */
    public static byte[] getBytesKey(Object object){
        if(object instanceof String){
            return getBytes((String)object);
        }else{
            return serialize(object);
        }
    }

    /**
     * 获取byte[]类型Key
     * @param key
     * @return
     */
    public static Object getObjectKey(byte[] key){
        try{
            try {
                return new String(key, CHARSET_NAME);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }catch(UnsupportedOperationException uoe){
            try{
                return JedisUtils.toObject(key);
            }catch(UnsupportedOperationException uoe2){
                uoe2.printStackTrace();
            }
        }
        return null;
    }

    /**
     * Object转换byte[]类型
     * @param key
     * @return
     */
    public static byte[] toBytes(Object object){
        return serialize(object);
    }

    /**
     * byte[]型转换Object
     * @param key
     * @return
     */
    public static Object toObject(byte[] bytes){
        return unserialize(bytes);
    }
    /**
     * 序列化对象
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            if (object != null){
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(object);
                return baos.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 转换为字节数组
     * @param str
     * @return
     */
    public static byte[] getBytes(String str){
        if (str != null){
            try {
                return str.getBytes(CHARSET_NAME);
            } catch (UnsupportedEncodingException e) {
                return null;
            }
        }else{
            return null;
        }
    }
    /**
     * 反序列化对象
     * @param bytes
     * @return
     */
    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            if (bytes != null && bytes.length > 0){
                bais = new ByteArrayInputStream(bytes);
                ObjectInputStream ois = new ObjectInputStream(bais);
                return ois.readObject();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
 
  
  • 6、测试代码。
package com.wqq;


public class Test {
    public static void main(String[] args) {

        //Tomcat容器启动初始化start
        TaskQueueDaemonThread taskQueueDaemonThread=TaskQueueDaemonThread.getInstance();
        taskQueueDaemonThread.init();
        //Tomcat容器启动初始化end

        //任务添加start
        /*for(int i=1;i<100000;i++){
            Student s=new Student();
            s.setId((long)i);
            //任务名称,同一类型任务名字相同
            s.setTaskName("sms");
            //任务延迟时间
            s.setDelayTime(i*2+"00");
            //当前时间ms值
            s.setAddTimeMillis(System.currentTimeMillis());

            //任务数据
            s.setName("李四"+i);
            taskQueueDaemonThread.put(Long.parseLong(s.getDelayTime()),s);
        }
        System.out.println("添加完成");*/
        Student s=new Student();
        s.setId((long)2);
        //任务名称,同一类型任务名字相同
        s.setTaskName("sms");
        //任务延迟时间
        s.setDelayTime(10+"000");
        //当前时间ms值
        s.setAddTimeMillis(System.currentTimeMillis());

        //任务数据
        s.setName("Survey"+10);
        taskQueueDaemonThread.put(Long.parseLong(s.getDelayTime()),s);
        //任务添加end
    }
}
  • 相关链接
  • redis本地安装https://blog.csdn.net/sinat_38273626/article/details/79923430
  • 所需jar包https://download.csdn.net/download/sinat_38273626/10442674
  • 源代码https://download.csdn.net/download/sinat_38273626/10563067

你可能感兴趣的:(java,Redis)