Redis的Spring配置讲解

来源:互联网 发布:淘宝宝贝没排名 编辑:程序博客网 时间:2024/04/29 06:59

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@EnableCachingpublic 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 描述具有简单值的条目 opsForList() ListOperations 操作具有list值的条目 opsForSet() SetOperations 操作具有set值的条目 opsForZSet() ZSetOperations 操作具有ZSet值(排序的set)的条目 opsForHash() HashOperations 操作具有hash值的条目 boundValueOps(K) BoundValueOperations 以绑定指定key的方式,操作具有简单值的条目 boundListOps(K) BoundListOperations 以绑定指定key的方式,操作具有list的条目 boundSetOps(K) BoundSetOperations 以绑定指定key的方式,操作具有set的条目 boundZSet(K) BoundZSetOperations 以绑定指定key的方式,操作具有ZSet(排序的set)的条目 boundHashOps(K) BoundHashOperations 以绑定指定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;@Controllerpublic 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是cartBoundListOperations<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的一些共有属性

属性 类型 描述 value String[] 要使用的缓存名称 condition String SpEL表达式,如果得到的值是false的话,不会将缓存应用到方法调用上 key String SpEL表达式,用来计算自定义的缓存key unless String SpEL表达式,如果得到的值是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的返回值,他将会作为放在缓存中的条目

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

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

http://7xp64w.com1.z0.glb.clouddn.com/qrcode_for_gh_3e33976a25c9_258.jpg

0 0
原创粉丝点击