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描述具有简单值的条目
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;

@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网站

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

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Redis Spring是指在Spring框架中使用Redis数据库的方式。SpringRedis的操作进行了封装,提供了RedisTemplate对象来进行对Redis的各种操作,并支持所有的Redis原生的API。RedisTemplate位于spring-data-redis包下,它是一个类,继承自RedisAccessor类,而RedisAccessor类又继承自Object类。 在Spring中使用Redis,需要在配置文件(如redis.properties)中设置相关的参数,如最大连接数、最大空闲连接数、最大等待时间、主机地址、端口号、超时时间、密码等。然后通过RedisTemplate进行操作Redis数据库。 RedisTemplate可以用来操作Redis的五种数据结构,分别是字符串(String)、哈希(Hash)、列表(List)、集合(Set)和有序集合(Sorted Set)。通过RedisTemplate,可以对这些数据结构进行添加、修改、删除、查询等操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [SpringRedis使用](https://blog.csdn.net/weixin_38626799/article/details/107047249)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [SpringRedis整合详解](https://blog.csdn.net/feiyangtianyao/article/details/87619128)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值