Java Redis缓存操作(哨兵模式)

8 篇文章 0 订阅

一、添加jedis的maven依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

二、在配置cache.properties文件中配置哨兵模式redis信息

# 单节点配置
#redis.host = 127.0.0.1
#redis.port = 6379

# 集群节点,集群模式下配置
#redis.cluster.nodes = 12.2.3.14:7001,12.2.3.14:7002,12.2.3.14:7003,12.2.3.14:7004

# 哨兵节点,哨兵模式下配置
redis.sentinel.nodes = 12.2.3.14:7001,12.2.3.14:7002,12.2.3.14:7003,12.2.3.14:7004
redis.sentinel.master = mymaster

# ----redis common begin----
# 密码
#redis.password = 123456
# 连接超时时间 单位 ms(毫秒)
redis.timeout = 6000
# 连接池中的最大空闲连接,默认值也是8
redis.pool.max-idle = 8
# 连接池中的最小空闲连接,默认值也是0
redis.pool.min-idle = 0
# 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
redis.pool.max-active = 8
# 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出
redis.pool.max-wait = -1
# ----redis common end----

三、定义CacheConfig类来加载配置信息

package com.ldy.common.cache;

/**
 * @author lidongyang
 * @Description 缓存配置类
 * @date 2019/6/21 8:38
 */
public class CacheConfig {

    /**
     * 单节点REDIS 地址
     */
    public static String REDIS_HOST = PropertiesUtils.getProperty("cache-config", "redis.host");

    /**
     * 单节点REDIS 端口
     */
    public static int REDIS_PORT = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.port"));

    /**
     * 集群模式节点
     */
    public static String REDIS_CLUSTER_NODES = PropertiesUtils.getProperty("cache-config", "redis.cluster.nodes");

    /**
     * 哨兵模式节点
     */
    public static String REDIS_SENTINEL_NODES = PropertiesUtils.getProperty("cache-config", "redis.sentinel.nodes");

    /**
     * 哨兵模式 master
     */
    public static String REDIS_SENTINEL_MASTER = PropertiesUtils.getProperty("cache-config", "redis.sentinel.master");

    /**
     * REDIS 密码
     */
    public static String REDIS_PASSWORD = PropertiesUtils.getProperty("cache-config", "redis.password");

    /**
     * REDIS 连接超时时间 单位 ms(毫秒)
     */
    public static int REDIS_TIMEOUT = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.timeout"));

    /**
     * 连接池中的最大空闲连接,默认值也是8
     */
    public static int REDIS_POOL_MAX_IDLE = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.max-idle"));

    /**
     * 连接池中的最小空闲连接,默认值也是0
     */
    public static int REDIS_POOL_MIN_IDLE = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.min-idle"));


    /**
     * # 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
     */
    public static int REDIS_POOL_MAX_ACTIVE = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.max-active"));

    /**
     * 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出
     */
    public static int REDIS_POOL_MAX_WAIT = Integer.parseInt(PropertiesUtils.getProperty("cache-config", "redis.pool.max-wait"));

}
上面使用到的PropertiesUtils代码如下:
package com.ldy.common.cache;
import java.io.InputStream;
import java.util.Properties;


/**
 *
 * PropertiesUtils.java
 * @desc properties 资源文件解析工具
 * @author lidongyang
 *
 */
public class PropertiesUtils {
	 private static Properties props; 
	  
	    private static void readProperties(String fileName) { 
	    	InputStream fis = null;
	    	try { 
	            props = new Properties(); 
	            fis =PropertiesUtils.class.getClassLoader().getResourceAsStream(fileName); 
	            props.load(fis); 
	        } catch (Exception e) { 
	            e.printStackTrace(); 
	        } finally{
	        	if(fis != null){
	        		try {
	        			fis.close();
	        		}catch(Exception e) { 
	    	            e.printStackTrace(); 
	    	        }
	        	}
	        	
	        }
	    } 
	    
	    /**
	     * 根据文件名和属性名获取属性值
	     * @author lidongyang
	     * @param fileName
	     * @param key
	     * @return
	     */
	    public synchronized static String getProperty(String fileName,String key){ 
	    	readProperties(fileName+".properties");
	    	return props.getProperty(key); 
	    } 
	   
	    public static void main(String[] args) {
	        String value = PropertiesUtils.getProperty("webconfig", "zip_path"); 
	        System.out.println("value:"+value);
	    }     
}

四、编写RedisSentinelCache类用来操作redis

package com.ldy.common.cache;


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

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @author lidongyang
 * @Description 哨兵模式redis缓存接口
 * @date 2019/6/20 16:45
 */
public class RedisSentinelCache {

    private static JedisSentinelPool redisSentinelJedisPool = null;

    public RedisSentinelCache() {
        if (null == redisSentinelJedisPool) {
            initPool();
        }
    }

    private void initPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(CacheConfig.REDIS_POOL_MAX_ACTIVE);
        config.setMaxIdle(CacheConfig.REDIS_POOL_MAX_IDLE);
        config.setMaxWaitMillis(CacheConfig.REDIS_POOL_MAX_WAIT);
        // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的
        config.setTestOnBorrow(true);
        //在return给pool时,是否提前进行validate操作
        config.setTestOnReturn(true);
        //在空闲时检查有效性,默认false
        config.setTestWhileIdle(true);
        // 哨兵模式
        String sentinelsStr = CacheConfig.REDIS_SENTINEL_NODES;
        Set<String> sentinels = new HashSet<String>();
        for (String sentinel : sentinelsStr.split(",")) {
            sentinels.add(sentinel);
        }
        redisSentinelJedisPool = new JedisSentinelPool(CacheConfig.REDIS_SENTINEL_MASTER, sentinels, config, CacheConfig.REDIS_PASSWORD);
    }

    /**
     * 同步获取Jedis实例
     *
     * @return
     */
    public synchronized  static Jedis getJedis() {
        return redisSentinelJedisPool.getResource();
    }


    public String get(String key) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            System.out.println("Jedis实例获取失败!");
            throw new RuntimeException();
        }

        try {
            return jedis.get(key);
        } catch (Exception e) {
            System.out.println("获取值失败:" + e.getMessage());
            throw new RuntimeException();
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }


    public Object getObject(String key) {
        Jedis jedis = getJedis();
        if (jedis == null) {
            System.out.println("Jedis实例获取失败!");
            throw new RuntimeException();
        }

        try {
            byte[] data = jedis.get(key.getBytes());
            return SerializeUtils.unserialize(data);
        } catch (Exception e) {
            System.out.println("获取值失败:" + e.getMessage());
            throw new RuntimeException();
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public void set(String key, String value) {
        Jedis jedis = getJedis();
        try {
            jedis.set(key, value);
        } catch (Exception e) {
            System.out.println("设置值失败:" + e.getMessage());
            throw new RuntimeException();
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public void set(String key, String value, int second) {
        Jedis jedis = getJedis();
        try {
            jedis.set(key, value);
            jedis.expire(key, second);
        } catch (Exception e) {
            System.out.println("设置值失败:" + e.getMessage());
            throw new RuntimeException();
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public void setObject(String key, Object value) {
        Jedis jedis = getJedis();
        try {
            jedis.set(key.getBytes(), SerializeUtils.serialize(value));
        } catch (Exception e) {
            System.out.println("设置值失败:" + e.getMessage());
            throw new RuntimeException();
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public void setObject(String key, Object value, int second) {
        Jedis jedis = getJedis();
        try {
            jedis.set(key.getBytes(), SerializeUtils.serialize(value));
            jedis.expire(key, second);
        } catch (Exception e) {
            System.out.println("设置值失败:" + e.getMessage());
            throw new RuntimeException();
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }

    public void del(String key) {
        Jedis jedis = getJedis();
        try {
            jedis.del(key);
        } catch (Exception e) {
            System.out.println("删除失败:" + e.getMessage());
            throw new RuntimeException();
        } finally {
            if (null != jedis) {
                jedis.close();
            }
        }
    }


    public static void main(String[] args) {
        RedisSentinelCache cache = new RedisSentinelCache();

        cache.set("ldy", "lisi");
        System.out.println(cache.get("lisi"));
        cache.del("lisi");

        cache.setObject("date", new Date());
        System.out.println(cache.getObject("date"));
    }
}

辅助工具类SerializeUtils代码如下

package com.ldy.common.cache;

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

/**
 * @author lidongyang
 * @Description 对象序列化工具类
 * @date 2019/6/20 18:51
 */
public class SerializeUtils {

    /**
     * 序列化
     * @param obj
     * @return
     */
    public static byte[] serialize(Object obj) {
        ByteArrayOutputStream byteOutputStream = null;
        ObjectOutputStream objectOutputStream = null;

        try {
            byteOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteOutputStream);

            objectOutputStream.writeObject(obj);
            objectOutputStream.flush();

            return byteOutputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != objectOutputStream) {
                try {
                    objectOutputStream.close();
                    byteOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return null;
    }


    /**
     * 反序列化
     * @param bytes
     * @return
     */
    public static Object unserialize(byte[] bytes) {
        ByteArrayInputStream byteInputStream = null;
        ObjectInputStream objectInputStream = null;

        try {
            byteInputStream = new ByteArrayInputStream(bytes);
            objectInputStream = new ObjectInputStream(byteInputStream);

            return objectInputStream.readObject();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != objectInputStream) {
                try {
                    objectInputStream.close();
                    byteInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值