SpringMVC整合Redis

Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。是目前企业项目中较多使用的缓存框架。将一些频繁使用的数据放入缓存读取;做session共享等。
XML方配置方式

 <!-- jedis 配置 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}" />
        <property name="minIdle" value="${redis.minIdle}" />
        <property name="maxWaitMillis" value="${redis.maxWait}" />
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
    </bean>
    <!-- redis服务器中心 -->
    <bean id="connectionFactory"
        class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="poolConfig" ref="poolConfig" />
        <property name="port" value="${redis.port}" />
        <property name="hostName" value="${redis.host}" />
        <property name="password" value="${redis.pass}" />
        <property name="timeout" value="${redis.timeout}" />
    </bean>
    <!-- redis操作模板,面向对象的模板 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <!-- 如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 -->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
        </property>
    </bean>

JavaConfig配置方式

package com.bigbigbu.cf.redis.config;

import javax.inject.Inject;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import redis.clients.jedis.JedisPoolConfig;

@EnableCaching  
@PropertySource("classpath:db.properties")
public class RedisConfig extends CachingConfigurerSupport {  

    @Inject
    Environment env;

    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig jc = new JedisPoolConfig();
        jc.setMaxTotal(env.getProperty("jedis.maxTotal", int.class, 10));
        jc.setMaxIdle(env.getProperty("jedis.maxIdle", int.class, 4));
        jc.setMinIdle(env.getProperty("jedis.minIdle", int.class, 1));
        jc.setMaxWaitMillis(env.getProperty("jedis.maxWaitMillis", int.class, 5000));
        jc.setMinEvictableIdleTimeMillis(env.getProperty("jedis.minEvictableIdleTimeMillis", int.class, 300000));
        jc.setNumTestsPerEvictionRun(env.getProperty("jedis.numTestsPerEvictionRun", int.class, 3));
        jc.setTimeBetweenEvictionRunsMillis(env.getProperty("jedis.timeBetweenEvictionRunsMillis", int.class, 60000));
        return jc;
    }

    @Bean  
    public JedisConnectionFactory redisConnectionFactory(JedisPoolConfig jpc) {  
        JedisConnectionFactory rcf = new JedisConnectionFactory();  
        rcf.setPoolConfig(jpc);
        // Defaults  
        rcf.setHostName(env.getProperty("redis.host"));  
        rcf.setPort(env.getProperty("redis.hostport", int.class, 6379));  
        rcf.setPassword(env.getProperty("redis.pass"));
        rcf.setUsePool(true);
        return rcf;  
    }  

    @Bean  
    public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory cf) {  

        //RedisTemplate<String, Object> aa;
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();  
        template.setConnectionFactory(cf);  
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
        template.setValueSerializer(new GenericToStringSerializer<>(Object.class));
        return template;  
    }  

    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {  
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);  
        // Number of seconds before expiration. Defaults to unlimited (0)  
        cacheManager.setDefaultExpiration(3000); // Sets the default expire time (in seconds)  
        return cacheManager;  
    }  

}  

基本方法封装

package com.bigbigbu.cf.redis;

import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import com.google.gson.Gson;

@Component
public class RedisClient {

    @Inject
    private RedisTemplate<String, Object> redisTemplate;

    public Long increment(String key,Long delta){
        ValueOperations<String, Object> redisOp = redisTemplate.opsForValue();
        return redisOp.increment(key, delta);
    }

    //默认10分钟过期
    public void set(String key, Object value){
        set(key, value, 10 * 60);
    }

    //秒为单位
    public void set(String key, Object value, int seconds){
        Gson gson = new Gson();
        ValueOperations<String, Object> redisOp = redisTemplate.opsForValue();
        if (value instanceof String){
            redisOp.set(key, value);
        }
        else{
            redisOp.set(key, gson.toJson(value));
        }

        expire(key, seconds);
    }

    public boolean expire(String key, int seconds){
        if (seconds > 0){
            return redisTemplate.expire(key, seconds, TimeUnit.SECONDS);
        }
        else{
            return false;
        }
    }

    public Object get(String key){
        ValueOperations<String, Object> redisOp = redisTemplate.opsForValue();
        return redisOp.get(key);
    }

    public void del(String key){
        redisTemplate.delete(key);
    }

    public Set<String> getKeys(String pattern){
        return redisTemplate.keys(pattern);
    }

    public <T> T get(String key, Class<T> clazz){
        String value = (String) get(key);
        if (clazz == String.class){
            return (T) value;
        }
        else{
            Gson gson = new Gson();
            return gson.fromJson(value, clazz);
        }
    }


    //默认10分钟过期
    public boolean setIfAbsent(String key, Object value){
        return setIfAbsent(key, value, 10 * 60);
    }

    //默认10分钟过期
    public boolean setIfAbsent(String key, Object value, int seconds){
        boolean rs = false;
        Gson gson = new Gson();
        ValueOperations<String, Object> redisOp = redisTemplate.opsForValue();
        if (value instanceof String){
            rs = redisOp.setIfAbsent(key, value);
        }
        else{
            rs = redisOp.setIfAbsent(key, gson.toJson(value));
        }

        if (rs == true) {
            expire(key, seconds);
        }
        return rs;
    }


}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值