redis使用

Posted inspred

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redis使用相关的知识,希望对你有一定的参考价值。

package com.yaming.hst.cache;

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

public class RedisUtil {
    
    private static String ADDR = "127.0.0.1";
    
    private static int PORT = 6379;
    
    private static String AUTH = "";
    
    private static int MAX_ACTIVE = 1024;
    
    private static int MAX_IDLE = 200;
    
    private static int MAX_WAIT =10000;
    
    private static int TIMEOUT = 10000;
    
    private static boolean TEST_ON_BORROW = true;
    
    private static JedisPool jedisPool = null;
    
    /**
     * 初始化连接池,
     * 参数根据项目实际情况配置
     */
    static{
        try{
            JedisPoolConfig config = new JedisPoolConfig();
            
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            
            jedisPool = new JedisPool(config,ADDR,PORT,TIMEOUT);
        }catch(Exception e){
            e.printStackTrace();
        }        
    }
    /**
     * 从连接池获取连接
     * @return
     */
    public synchronized static Jedis getJedis(){
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
                
            }else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * 连接用完后返回
     * @param jedis
     */
    public static void returnResource(final Jedis jedis){
        if(jedis != null){
            jedisPool.returnResource(jedis);
        }
    }
    
}
package com.yaming.hst.cache;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;

/**
 * Redis客户端
 * @author zWX537285
 *
 */
public class JedisClient {
    
    private static Jedis jedis;
    
    /**
     * 获取连接
     */
    public static void connectRedis(){
        jedis = RedisUtil.getJedis();
    }
    
    /**
     * 字符串
     * @param key
     * @param value
     * @return
     */
    public static String set(String key,String value){
        connectRedis();
        String result = jedis.set(key, value);
        disconnectRedis();
        return result;
    }
        
    /**
     * 获取字符串
     * @param key
     * @return
     */
    public static String get(String key){
        connectRedis();
        String result = jedis.get(key);
        disconnectRedis();
        return result;
    }
    
    
    /**
     * 设置hash
     * @param key
     * @param field
     * @param value
     * @return
     */
    public static Long hset(String key,String field,String value){
        connectRedis();
        Long result = jedis.hset(key, field, value);
        disconnectRedis();
        return result;
    }
    
    /**
     * 获取hash
     * @param key
     * @param field
     * @return
     */
    public static String hget(String key,String field){
        connectRedis();
        String result = jedis.hget(key, field);
        disconnectRedis();
        return result;
    }
    
    /**
     * 操作Map
     * @param key
     * @param hash
     * @return
     */
    public static String hmset(String key,Map<String, String> hash){
        connectRedis();
        String result = jedis.hmset(key, hash);
        disconnectRedis();
        return result;
    }
    
    /**
     * 从Map中取值
     * @param key
     * @param fields
     * @return
     */
    public static List<String> hmget(String key,String...fields){
        connectRedis();
        List<String> result = jedis.hmget(key, fields);
        disconnectRedis();
        return result;
    }
    
    /**
     * 自增长序号
     * @param key
     * @param field
     * @return
     */
    public static Long incr(String key){
        connectRedis();
        Long result = jedis.incr(key);
        disconnectRedis();
        return result;
    }
    
    /**
     * 返回排序结果,仅仅返回一个有序List,不改变原有数据的顺序。
     * @param key
     * @return
     */
    public static List<String> sort(String key){
        connectRedis();
        List<String> result = jedis.sort(key);
        disconnectRedis();
        return result;
    }
    
    /**
     * 存List,
     * 按照我们的习惯,数据从左向右存放
     * @param key
     * @param strings
     * @return
     */
    public static Long rpush(String key,String...strings){
        connectRedis();
        Long result = jedis.rpush(key, strings);
        disconnectRedis();
        return result;
    }
    
    /**
     * 取出List
     * 取出的数据,就是存放的数据
     * @param key
     * @return
     */
    public static List<String> lrange(String key){
        connectRedis();
        List<String> result = jedis.lrange(key, 0, -1);
        disconnectRedis();
        return result;
    }
    
    /**
     * 存入set
     * @param key
     * @param values
     * @return
     */
    public static Long sadd(String key,String...values){
        connectRedis();
        Long result = jedis.sadd(key,values);
        disconnectRedis();
        return result;
    }
    
    /**
     * 取出set中所有元素
     * @param key
     * @return
     */
    public static Set<String> smembers(String key){
        connectRedis();
        Set<String> result = jedis.smembers(key);
        disconnectRedis();
        return result;
    }
    
    /**
     * 获取Pipeline,用于批量处理
     * @param key
     * @return
     */
    public static Pipeline getPipeline(){
        connectRedis();
        Pipeline pipeline = jedis.pipelined();
        disconnectRedis();
        return pipeline;
    }
    
    /**
     * 删除key
     * @param key
     */
    public static Long del(String key){
        connectRedis();
        Long result = jedis.del(key);
        disconnectRedis();
        return result;
    }
    
    /**
     * 批量删除key
     * @param key
     * @return
     */
    public static void batchDel(String key){
        connectRedis();
        Set<String> set = jedis.keys(key +"*");
        Iterator<String> it = set.iterator();
        while(it.hasNext()){
            String keyStr = it.next();
            jedis.del(keyStr);
        }        
        disconnectRedis();
    }
    
    /**
     * 初始化zset
     * @param key
     * @param element
     */
    public static void initZset(String key,List<String> element){    
        connectRedis();
        for (int i = 0; i < element.size(); i++) {
            jedis.zadd(key, 0,element.get(i));
        }    
        disconnectRedis();        
    }
    
    /**
     * 改变score
     * @param key
     * @param score
     * @param element
     * @return
     */
    public static Double zincrby(String key,Integer score,String element){
        connectRedis();
        Double result = jedis.zincrby(key, score, element);
        disconnectRedis();
        return result;    
    }
    
    /**
     * zset结果集,正序输出--incr
     * @param key
     * @return
     */
    public static Set<String> zsetIncrList(String key){
        connectRedis();
        Set<String> result = jedis.zrange(key, 0, -1);
        disconnectRedis();
        return result;
    }
    
    /**
     * 倒序输出
     * @param key
     * @return
     */
    public static Set<String> zsetDescList(String key){
        connectRedis();
        Set<String> result = jedis.zrevrange(key, 0, -1);
        disconnectRedis();
        return result;
    }
    
    /**
     * 返回连接
     */
    public static void disconnectRedis(){
        RedisUtil.returnResource(jedis);
    }
    
}

序列化为json:

package com.yaming.hst.cache;
 
import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
 
/**
 * Json<--->Object工具类
 * @author zWX537285
 *
 */
public class JsonUtils {
 
    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();
 
    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
        try {
            String string = MAPPER.writeValueAsString(data);
            return string;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData json数据
     * @param clazz 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = MAPPER.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return null;
    }
    
}

序列化方式二:

package com.yaming.hst.cache;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 序列化对象工具类,用于保存和读取redis数据使用
 * @author zWX537285
 *
 */
public class SerializeUtil  {

    private static Logger log = LoggerFactory.getLogger(SerializeUtil.class);  

    /**
     * 序列化对象
     * @param object
     * @return
     */
    public static byte[] serialize(Object object) {  
        ObjectOutputStream oos = null;  
        ByteArrayOutputStream baos = null;  
        byte[] bytes = null;
        try {  
            // 序列化  
            baos = new ByteArrayOutputStream();  
            oos = new ObjectOutputStream(baos);  
            oos.writeObject(object);  
            bytes = baos.toByteArray();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (oos != null) {  
                    oos.close();  
                }  
                if (baos != null) {  
                    baos.close();  
                }  
            } catch (Exception e2) {  
                e2.printStackTrace();  
            }  
        }  
        return bytes;  
    }  

    /**
     * 反序列化对象
     * @param bytes
     * @return
     */
    public static Object unserialize(byte[] bytes) { 
        Object obj = null; 
        ByteArrayInputStream bais = null;  
        try {  
            // 反序列化  
            bais = new ByteArrayInputStream(bytes);  
            ObjectInputStream ois = new ObjectInputStream(bais);  
            obj = ois.readObject();  
            ois.close();   
            bais.close();
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return obj;  
    }  

    /**
     * 关闭的数据源或目标。调用 close()方法可释放对象保存的资源(如打开文件)
     * 关闭此流并释放与此流关联的所有系统资源。如果已经关闭该流,则调用此方法无效。
     * @param closeable
     */
    public static void close(Closeable closeable) {  
        if (closeable != null) {  
            try {  
                closeable.close();  
            } catch (Exception e) {  
                log.info("Unable to close %s", closeable, e);  
            }  
        }  
    }

    /**
     * 列表序列化(用于Redis整存整取)
     * @param value
     * @return
     */
    public static <T> byte[] serialize(List<T> value) {  
        if (value == null) {  
            throw new NullPointerException("Can‘t serialize null");  
        }  
        byte[] rv=null;  
        ByteArrayOutputStream bos = null;  
        ObjectOutputStream os = null;  
        try {  
            bos = new ByteArrayOutputStream();  
            os = new ObjectOutputStream(bos);  
            for(T obj : value){  
                os.writeObject(obj);  
            }  
            os.writeObject(null);  
            os.close();  
            bos.close();  
            rv = bos.toByteArray();  
        } catch (IOException e) {  
            throw new IllegalArgumentException("Non-serializable object", e);  
        } finally {  
            close(os);
            close(bos);
        }  
        return rv;  
    }

    /**
     * 反序列化列表(用于Redis整存整取)
     * @param in
     * @return
     */
    public static <T> List<T> unserializeForList(byte[] in) {  
        List<T> list = new ArrayList<T>();  
        ByteArrayInputStream bis = null;  
        ObjectInputStream is = null;  
        try {  
            if(in != null) {  
                bis=new ByteArrayInputStream(in);  
                is=new ObjectInputStream(bis);  
                while (true) {  
                    T obj = (T) is.readObject();  
                    if(obj == null){  
                        break;  
                    }else{  
                        list.add(obj);  
                    }  
                }  
                is.close();  
                bis.close();  
            }  
        } catch (IOException e) {  
            log.warn("Caught IOException decoding %d bytes of data",  
                    in == null ? 0 : in.length, e);  
        } catch (ClassNotFoundException e) {  
            log.warn("Caught CNFE decoding %d bytes of data",  
                    in == null ? 0 : in.length, e);  
        } finally {  
            close(is);  
            close(bis);  
        }  
        return list;  
    }  

}

依赖:

<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
        </dependency>

 

以上是关于redis使用的主要内容,如果未能解决你的问题,请参考以下文章

Redis实现分布式锁(设计模式应用实战)

Redis实现分布式锁(设计模式应用实战)

redis存储session配制方法

Redis 学习 —— 数据类型及操作

Redis学习之列表类型详解

微信小程序代码片段