Nemo

Nemo 关注TA

路漫漫其修远兮,吾将上下而求索。

Nemo

该文章投稿至Nemo社区   Java  板块 复制链接


redis + Spring简单配置

发布于 2016/09/13 17:03 4,512浏览 0回复 7,205

最近在做redis的缓存这块,目前用Ubuntu server做了一个简单的redis server,在程序中集成了redis的支持配置,接下来需要做下redis集群管理和redis查询这块的内容,这里先把基本的配置稍稍记录下,接下来还需要对这部分内容做进一步的优化:


Spring-redis.xml:

======================================

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
       default-lazy-init="false">

    <!-- 连接池配置. -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!-- 连接池中最大连接数。高版本:maxTotal,低版本:maxActive -->
        <property name="maxTotal" value="8" />
        <!-- 连接池中最大空闲的连接数. -->
        <property name="maxIdle" value="4" />
        <!-- 连接池中最少空闲的连接数. -->
        <property name="minIdle" value="1" />
        <!-- 当连接池资源耗尽时,调用者最大阻塞的时间,超时将跑出异常。单位,毫秒数;默认为-1.表示永不超时。高版本:maxWaitMillis,低版本:maxWait -->
        <property name="maxWaitMillis" value="5000" />
        <!-- 连接空闲的最小时间,达到此值后空闲连接将可能会被移除。负值(-1)表示不移除. -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
        <!-- 对于“空闲链接”检测线程而言,每次检测的链接资源的个数。默认为3 -->
        <property name="numTestsPerEvictionRun" value="3" />
        <!-- “空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1. -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- testOnBorrow:向调用者输出“链接”资源时,是否检测是有有效,如果无效则从连接池中移除,并尝试获取继续获取。默认为false。建议保持默认值. -->
        <!-- testOnReturn:向连接池“归还”链接时,是否检测“链接”对象的有效性。默认为false。建议保持默认值.-->
        <!-- testWhileIdle:向调用者输出“链接”对象时,是否检测它的空闲超时;默认为false。如果“链接”空闲超时,将会被移除。建议保持默认值. -->
        <!-- whenExhaustedAction:当“连接池”中active数量达到阀值时,即“链接”资源耗尽时,连接池需要采取的手段, 默认为1(0:抛出异常。1:阻塞,直到有可用链接资源。2:强制创建新的链接资源) -->
    </bean>

    <!-- Spring提供的Redis连接工厂 -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy">
        <!-- 连接池配置. -->
        <property name="poolConfig" ref="jedisPoolConfig" />
        <!-- Redis服务主机. -->
        <property name="hostName" value="172.20.98.250" />
        <!-- Redis服务端口号. -->
        <property name="port" value="6379" />
        <!-- Redis服务连接密码. -->
         <property name="password" value="12345a*" />
        <!-- 连超时设置. -->
        <property name="timeout" value="15000" />
        <!-- 是否使用连接池. -->
        <property name="usePool" value="true" />
    </bean>

    <!-- Spring提供的访问Redis类. -->
    <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory" />
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <!-- <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> -->
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
        </property>
    </bean>

</beans>

RedisCacheUtil

==========================================

package com.ict.web.commons.redis;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

@Service
public class RedisCacheUtil<T>
{
    @Autowired @Qualifier("jedisTemplate")
    private RedisTemplate<Serializable, Object> redisTemplate;
    private Long defaultCacheExpireTime = 10l; // 缓存默认的过期时间,这里设置了10秒

    public Object invoke(MethodInvocation invocation) throws Throwable {
        Object value = null;

        String targetName = invocation.getThis().getClass().getName();
        String methodName = invocation.getMethod().getName();

        Object[] arguments = invocation.getArguments();
        String key = getCacheKey(targetName, methodName, arguments);

        try {
            // 判断是否有缓存
            if (exists(key)) {
                return getCache(key);
            }
            // 写入缓存
            value = invocation.proceed();
            if (value != null) {
                final String tkey = key;
                final Object tvalue = value;
                new Thread(new Runnable() {
                    public void run() {
                        setCache(tkey, tvalue, defaultCacheExpireTime);
                    }
                }).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (value == null) {
                return invocation.proceed();
            }
        }
        return value;
    }

    /**
     * 创建缓存key
     *
     * @param targetName
     * @param methodName
     * @param arguments
     */
    private String getCacheKey(String targetName, String methodName,
                               Object[] arguments) {
        StringBuffer sbu = new StringBuffer();
        sbu.append(targetName).append("_").append(methodName);
        if ((arguments != null) && (arguments.length != 0)) {
            for (int i = 0; i < arguments.length; i++) {
                sbu.append("_").append(arguments[i]);
            }
        }
        return sbu.toString();
    }



    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object getCache(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate
                .opsForValue();
        try {
            result = operations.get(key);
        }catch (Exception e){
            return null;
        }
        return result;
    }



    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean setCache(final String key, Object value, Long expireTime) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate
                    .opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}

点赞(0)
点了个评