Spring缓存机制整合Redis

本文介绍了如何在Spring中整合Redis作为缓存机制。针对XML和Java配置两种方式,详细解析了配置连接池、连接工厂、序列化器、RedisTemplate和缓存管理器的步骤。还展示了如何在RoleService接口的增删改查方法上应用@Cacheable、@CachePut和@CacheEvict注解,以及测试代码和日志监控。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

首先,在Spring中使用Redis需要jedis.jar和spring-data-redis.jar

Spring整合Redis有两种方式,一种为注解,另一种为xml配置文件,根据你的Spring IoC配置形式进行选择,下面来分别进行讲解:

如果你的IoC容器是以xml文件形式配置的,则在你的IoC配置文件中加入如下代码:

<!-- 配置连接池 -->
       <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
           <property name="maxIdle" value="50"/>
           <property name="maxTotal" value="100"/>
           <property name="maxWaitMillis" value="20000"/>
       </bean>
                  
       <!-- 配置连接工厂 -->
       <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
           <property name="hostName" value="localhost"/>
           <property name="port" value="6379"/>
           <property name="poolConfig" ref="poolConfig"/>
       </bean>
    <!-- 键值序列化器 -->
       <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
       <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
       <!-- 配置redisTemplate -->
       <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
           <property name="connectionFactory" ref="connectionFactory"/>
           <!-- 设置默认的序列化器为字符串序列化 -->
           <property name="defaultSerializer" ref="stringRedisSerializer"/>
           <property name="keySerializer" ref="stringRedisSerializer"/>
           <property name="valueSerializer" ref="jdkSerializationRedisSerializer"/>
           <property name="hashKeySerializer" ref="stringRedisSerializer"/>
           <property name="hashValueSerializer" ref="jdkSerializationRedisSerializer"/>
       </bean>
       <!-- 使用注解驱动,其中属性cache-manager默认值为cacheManager -->
       <cache:annotation-driven cache-manager="redisCacheManager"/>
       <!-- 定义缓存管理器 -->
       <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值