redis缓存存储、删除、查找、更新

1,实际工程代码

配置文件 bootstrap.properties

redis.database=0
redis.host={sc}
redis.port=6379

接口

package com.mylib.elba.cache.service;
import com.mylib.elba.cache.entity.CacheManage;
import com.mylib.Pageable;
import com.mylib.sql.QueryFilter;

/**
 * @author ljj
 *
 */
public interface CacheManageService {
       //存储一个对象进入redis
    String createCache(CacheManage cache);
       //根据过滤条件查询缓存,并返回分页
    Pageable<CacheManage> getAllRedis(QueryFilter query, int page, int pageSize);
        //根据key值模糊查询,并返回分页(性能较好)
    Pageable<CacheManage> getCache(String key, int page, int pageSize);
        //  改变存在redis中对象的某一个属性的值(state属性)
    void changeStateInval(String key);
    void changeStateVal(String key);
        //根据key删除
    void delCache(String key);
}

实现类

package com.mylib.elba.cache.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.mylib.elba.cache.entity.CacheManage;
import com.mylib.elba.cache.inner.PropertyUtil;
import com.mylib.elba.cache.service.CacheManageService;
import mylib.Pageable;
import com.mylib.sql.Command;
import com.mylib.sql.QueryFilter;
import com.mylib.util.SerializeUtil;

import redis.clients.jedis.Jedis;

/**
 * @author ljj
 *
 */
@Service
public class CacheManageServiceImpl implements CacheManageService {

    private static String path = "";
    private static int port;
    private static int database;
    // 日期格式化
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static {
        // 配置文件只加载一次
        Properties properties = PropertyUtil.loadProperties("bootstrap.properties");
        path = properties.getProperty("redis.host");
        port = Integer.parseInt(properties.getProperty("redis.port"));
        database = Integer.parseInt(properties.getProperty("redis.database"));
    }

    private Jedis redisInit() {
        Jedis redis = new Jedis(path, port);
        // redis的指定数据库
        redis.select(database);
        return redis;
    }

    @Override
    public Pageable<CacheManage> getAllRedis(QueryFilter query, int page, int pageSize) {
        Jedis redis = redisInit();
        // 获取所有key
        Set<String> keys = redis.keys("*");
        List<CacheManage> list = new ArrayList<CacheManage>();
        for (String key : keys) {
            byte[] value = redis.get(key.getBytes());
            Object object = SerializeUtil.unserialize(value);
            if (object != null) {
                CacheManage cache = (CacheManage) object;
                list.add(cache);
            }
        }
        redis.close();

        // 处理过滤查询
        List<CacheManage> queryList = queryFromRedis(query, list);
        // 处理分页
        Pageable<CacheManage> pageList = paging(queryList, page, pageSize);

        return pageList;
    }

    // 处理过滤查询
    public List<CacheManage> queryFromRedis(QueryFilter query, List<CacheManage> list) {
        List<CacheManage> queryList = new ArrayList<CacheManage>();
        for (CacheManage cache : list) {
            if (queryFlag(query, cache)) {
                queryList.add(cache);
            }
        }
        return queryList;
    }

    // 判断单个缓存是否符合过滤条件
    public boolean queryFlag(QueryFilter query, CacheManage cache) {
        for (Command command : query.getCommands()) {
            String comValue = command.getValue().toString();
            String comField = command.getField();
            if (comField.equals("root_System") && !cache.getRootSystem().contains(comValue)) {
                return false;
            }
            if (comField.equals("key") && !cache.getKey().contains(comValue)) {
                return false;
            }
            if (comField.equals("value") && !cache.getValue().contains(comValue)) {
                return false;
            }
            if (comField.equals("state")) {
                // 2表示全选
                if (!comValue.equals("2") && !cache.getState().equals(comValue)) {
                    return false;
                }
            }
            // 时间段
            if (comField.equals("end_Time")) {
                // 根据时间段查询
                if (comValue.equals("undefined~undefined")) {
                    continue;
                }
                Date date = cache.getEndTime();
                if (null == date) {
                    return false;
                }
                String[] array = comValue.toString().split("~");
                String datefrom = array[0];
                String dateto = array[1];
                try {
                    if (!datefrom.equals("undefined") && sdf.parse(datefrom).getTime() > date.getTime()) {
                        return false;
                    }
                    if (!dateto.equals("undefined") && sdf.parse(dateto).getTime() < date.getTime()) {
                        return false;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;
    }

    // 将list分页
    public Pageable<CacheManage> paging(List<CacheManage> list, int page, int pageSize) {
        if (list != null && list.size() > 0) {
            int totalcount = list.size();
            int fromIndex = (page - 1) * pageSize;
            int toIndex = page * pageSize;
            if (fromIndex > totalcount) {
                return null;
            }
            if (toIndex > totalcount) {
                toIndex = totalcount;
            }
            List<CacheManage> subList = list.subList(fromIndex, toIndex);
            Pageable<CacheManage> pageList = new Pageable<CacheManage>(page, pageSize, totalcount, subList);
            return pageList;
        } else {
            return null;
        }

    }

    @Override
    public void changeStateInval(String key) {
        Jedis redis = redisInit();
        // 有效(1)变无效(0)
        byte[] value = redis.get(key.getBytes());
        Object object = SerializeUtil.unserialize(value);
        if (object != null) {
            CacheManage cache = (CacheManage) object;
            cache.setState("0");
            cache.setEndTime(new Date());
            // 删除之前的值
            if (redis.exists(key)) {
                redis.del(key);
            }
            redis.set(cache.getKey().getBytes(), SerializeUtil.serialize(cache), "NX".getBytes());
        }
        redis.close();
    }

    @Override
    public void changeStateVal(String key) {
        Jedis redis = redisInit();
        // 无效(0)变无效(1)
        byte[] value = redis.get(key.getBytes());
        Object object = SerializeUtil.unserialize(value);
        if (object != null) {
            CacheManage cache = (CacheManage) object;
            cache.setState("1");
            cache.setEndTime(null);
            // 删除之前的值
            if (redis.exists(key)) {
                redis.del(key);
            }
            redis.set(cache.getKey().getBytes(), SerializeUtil.serialize(cache), "NX".getBytes());
        }
        redis.close();
    }

    @Override
    public void delCache(String key) {
        Jedis redis = redisInit();
        if (redis.exists(key)) {
            redis.del(key);
        }
        redis.close();
    }

    // 建立缓存对外接口实现
    @Override
    public String createCache(CacheManage cache) {
        Jedis redis = redisInit();
        cache.setCreateDate(new Date());
        // 状态 :0 无效,1有效,存的时候默认有效
        cache.setState("1");

        // 均为永久保存
        String result = redis.set(cache.getKey().getBytes(), SerializeUtil.serialize(cache), "NX".getBytes());
        redis.close();
        return result;
    }

    // 获取缓存对外接口实现
    @Override
    public Pageable<CacheManage> getCache(String key, int page, int pageSize) {
        // 获取所有key
        Jedis redis = redisInit();

        Set<String> keys = redis.keys("*" + key + "*");
        List<CacheManage> list = new ArrayList<CacheManage>();
        for (String itm : keys) {
            byte[] value = redis.get(itm.getBytes());
            Object object = SerializeUtil.unserialize(value);
            if (object != null) {
                CacheManage cache = (CacheManage) object;
                list.add(cache);
            }
        }
        redis.close();

        // 处理分页
        Pageable<CacheManage> pageList = paging(list, page, pageSize);

        return pageList;
    }

}

2,redis储存对象需要用到的序列化类

package com.mylib.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
    public static byte[] serialize(Object object) {
        if (object == null) {
            return new byte[0];
        } else {
            ObjectOutputStream oos = null;
            ByteArrayOutputStream baos = null;

            try {
                baos = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(baos);
                oos.writeObject(object);
                byte[] e = baos.toByteArray();
                return e;
            } catch (Exception arg3) {
                throw new RuntimeException(arg3.getMessage(), arg3);
            }
        }
    }

    public static Object unserialize(byte[] bytes) {
        if (bytes != null && bytes.length != 0) {
            ByteArrayInputStream bais = null;

            try {
                bais = new ByteArrayInputStream(bytes);
                ObjectInputStream e = new ObjectInputStream(bais);
                return e.readObject();
            } catch (Exception arg2) {
                throw new RuntimeException(arg2.getMessage(), arg2);
            }
        } else {
            return null;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值