Spring + Jedis集成Redis(單例redis數據庫)


這幾天沒事,就把之前學習的redis代碼整理一遍,廢話不多說,上步驟。

1、pom.xml引入資源;

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.7.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.0</version>
        </dependency>

2、配置redis的配置文件,這里只配置單點數據庫,后面會介紹redis集群的配置,這里就不多說了;

 spring-redis.xml配置:

    <!-- 讀取配置文件信息 -->
    <context:property-placeholder ignore-unresolvable="true" location="classpath:*.properties"/>

    <!-- Redis 配置 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxActive}" />
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
        <property name="testOnBorrow" value="true" />
    </bean>

    <!-- redis單節點數據庫連接配置 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}" />
        <property name="port" value="${redis.port}" />
        <property name="password" value="${redis.password}" />
        <property name="poolConfig" ref="jedisPoolConfig" />
    </bean>

    <!-- redisTemplate配置,redisTemplate是對Jedis的對redis操作的擴展,有更多的操作,封裝使操作更便捷 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
    </bean>

 redis.properties文件配置:

#redis的服務器地址
redis.host=這里寫你的ip
#redis的服務端口
redis.port=6379
#密碼
redis.password=這里寫你的密碼
#鏈接數據庫
redis.default.db=0
#客戶端超時時間單位是毫秒
redis.timeout=100000
#最大連接數
redis.maxActive=300
#最大空閑數
redis.maxIdle=100
#最大建立連接等待時間
redis.maxWaitMillis=1000

3、接着,具體實現代碼;

 序列化和反序列化工具類:

public class SerializerUtil {

    /**
     * 序列化
     * @param object
     * @return
     */
    public static byte[] serializeObj(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {
            throw new RuntimeException("序列化失敗!", e);
        }
    }

    /**
     * 反序列化
     * @param bytes
     * @return
     */
    public static Object deserializeObj(byte[] bytes) {
        if (bytes == null){
            return null;
        }
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
            throw new RuntimeException("反序列化失敗!", e);
        }
    }
}

操作實現類,這里只提供了3個實現方法,其他的可以按照自己需求自己實現:

@Component
public class RedisCache {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 添加緩存數據
     * @param key
     * @param obj
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> boolean putCache(String key, T obj) throws Exception {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = SerializerUtil.serializeObj(obj);
        boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.setNX(bkey, bvalue);
            }
        });
        return result;
    }

    /**
     * 添加緩存數據,設定緩存失效時間
     * @param key
     * @param obj
     * @param expireTime
     * @param <T>
     * @throws Exception
     */
    public <T> void putCacheWithExpireTime(String key, T obj, final long expireTime) throws Exception {
        final byte[] bkey = key.getBytes();
        final byte[] bvalue = SerializerUtil.serializeObj(obj);
        redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                connection.setEx(bkey, expireTime, bvalue);
                return true;
            }
        });
    }

    /**
     * 根據key取緩存數據
     * @param key
     * @param <T>
     * @return
     * @throws Exception
     */
    public <T> T getCache(final String key) throws Exception {
        byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
            @Override
            public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.get(key.getBytes());
            }
        });
        if (result == null) {
            return null;
        }
        return (T) SerializerUtil.deserializeObj(result);
    }
}

4、測試代碼;

    @Test
    public void test7() throws Exception{
        List<String> list = new ArrayList<String>();
        list.add("測試list");
        list.add("測試list2");
        
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("test*","測試數據");
        map.put("測試數據","啥的");
        map.put("listTest",list);
        redisCache.putCache("testMap",map);

        Map<String,Object> mapResult = redisCache.getCache("testMap");
        System.out.print(mapResult.toString());

    }

結果:

5、OK,一切正常。ps:有興趣的同學可以去看看redis源碼,挺好!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM