Redis的Spring配置讲解

Redis是一种特殊类型的数据库,他被称之为key-value存储

本文覆盖缓存和存储两方面进行说明,使用的是Spring 4.0和Java配置方式

代码地址下载地址:https://github.com/zoeminghong/springmvc-javaconfig

存储

Redis的配置

package springmvc.rootconfig;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

@Configuration
@EnableCaching
public class CachingConfig {

    /**
     * 连接Redis
     * 
     * @return
     */
    @Bean
    public JedisConnectionFactory redisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        // host地址
        jedisConnectionFactory.setHostName("10.10.13.12");
        // 端口号
        jedisConnectionFactory.setPort(6379);
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }

    /**
     * RedisTemplate配置
     * 
     * @param redisCF
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(
            RedisConnectionFactory redisCF) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(redisCF);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

Redis连接工厂

  • JedisConnectionFactory

  • JredisConnectionFactory

  • LettuceConnectionFactory

  • SrpConnectionFactory

建议自行测试选用合适自己的连接工厂

如果使用的是localhost和默认端口,则这两项的配置可以省略

RedisTemplate

  • RedisTemplate

  • StringRedisTemplate

RedisTemplate能够让我们持久化各种类型的key和value,并不仅限于字节数组

StringRedisTemplate扩展了RedisTemplate,只能使用String类型

StringRedisTemplate有一个接受RedisConnectionFactory的构造器,因此没有必要在构建后在调用setConnectionFactory()

使用RedisTemplateAPI

方法子API接口描述
opsForValue()ValueOperations<K,V>描述具有简单值的条目
opsForList()ListOperations<K,V>操作具有list值的条目
opsForSet()SetOperations<K,V>操作具有set值的条目
opsForZSet()ZSetOperations<K,V>操作具有ZSet值(排序的set)的条目
opsForHash()HashOperations<K,HK,VH>操作具有hash值的条目
boundValueOps(K)BoundValueOperations<K,V>以绑定指定key的方式,操作具有简单值的条目
boundListOps(K)BoundListOperations<K,V>以绑定指定key的方式,操作具有list的条目
boundSetOps(K)BoundSetOperations<K,V>以绑定指定key的方式,操作具有set的条目
boundZSet(K)BoundZSetOperations<K,V>以绑定指定key的方式,操作具有ZSet(排序的set)的条目
boundHashOps(K)BoundHashOperations<K,V>以绑定指定key的方式,操作具有hash值的条目

操作

package springmvc.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import springmvc.bean.Order;
import springmvc.orders.db.OrderRepository;

@Controller
public class HomeController {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;
    @RequestMapping(value = { "/", "index" }, method = RequestMethod.GET)
    public String index() {
        redisTemplate.opsForValue().set("gege", 11);
        System.out.print(redisTemplate.opsForValue().get("gege"));
        return "index";
    }
}
//创建List条目,key是cart
BoundListOperations<String, Object>cart=redisTemplate.boundListOps("cart");
//删除最后的一条数据
cart.rightPop();
//在最后,添加一条数据
cart.rightPush("我笑了");

Key和Value序列化

如果要使用到JavaBean,需要其实现Serializable接口,将其序列化

或者使用Spring Data Redis提供的序列化器

  • GenericToStringSerializer:使用Spring转换服务进行序列化

  • JacksonJsonRedisSerializer:使用Jackson1,将对象序列化为JSON

  • Jackson2JsonRedisSerializer:使用Jackson2,将对象序列化为JSON

  • JdkSerializationRedisSerializer:使用Java序列化

  • OxmSerializer:使用Spring O/X映射的编排器和解排器实现序列化,用于XML序列化

  • StringRedisSerializer:序列化String类型的key和value

redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Order>(Order.class));

缓存

配置

在配置文件中追加如下代码

    /**
     * 缓存管理器
     * @param redisTemplate
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
        RedisCacheManager  cacheManager    =new RedisCacheManager(redisTemplate);
        //设置过期时间
        cacheManager.setDefaultExpiration(10);
        return cacheManager;

    }

使用注解进行缓存数据

注解描述
@Cacheable表明Spring在调用方法之前,首先应该在缓存中查找方法的返回值,如果这个值能够找到,就会返回缓存的值。否则,这个方法就会被调用,返回值会放到缓存之中
@CachePut表名Spring应该将方法的返回值放到缓存中。在方法的调用前并不会检查缓存,方法始终都会被调用
@CacheEvict表明Spring应该在缓存中清除一个或多个条目
@Caching这是一个分组的注解,能够同时应用多个其他的缓存注解

@Cacheable与@CachePut的一些共有属性

属性类型描述
valueString[]要使用的缓存名称
conditionStringSpEL表达式,如果得到的值是false的话,不会将缓存应用到方法调用上
keyStringSpEL表达式,用来计算自定义的缓存key
unlessStringSpEL表达式,如果得到的值是true的话,返回值不会放到缓存之中
package springmvc.orders.db;

import java.util.List;

import org.springframework.cache.annotation.Cacheable;

import springmvc.bean.Order;

public interface OrderOperations {
    @Cacheable("spittle")
    List<Order> findOrdersByType(String t);

}

缓存切面会拦截调用并在缓存中查找之前以名spittle存储的返回值。缓存的key是传递到findOrdersByType()方法中的t参数。如果按照这个key能够找到值的话,就会返回找到的值,方法就不会被调用。如果没有找到值的话,那么就会调用这个方法

当在接口方法添加注解后,被注解的方法,在所有的实现继承中都会有相同的缓存规则

@CacheEvict

@CacheEvict("spittle")
void remove(String Id);

@CacheEvict能够应用在返回值为void的方法上, 而@Cacheable和@CachePut需要非void的返回值,他将会作为放在缓存中的条目

属性类型描述
valueString[]要使用的缓存名称
keyStringSpEL表达式,用来计算自定义的缓存key
conditionStringSpEL表达式,如果得到的值是false的话,缓存不会应用到方法调用上
allEntriesboolean如果为true的话,特定缓存的所有条目都会被移除
beforeInvocationboolean如果为true的话,在方法调用之前移除条目,如果为false的话,在方法成功调用之后在移除条目

更多内容可以关注微信公众号,或者访问AppZone网站

《Redis的Spring配置讲解》

    原文作者:迹_Jason
    原文地址: https://segmentfault.com/a/1190000005885205
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞