spring redis 缓存

本文介绍如何将 Spring MVC 中的 ehcache 替换为 Redis 实现缓存功能,包括必要的依赖引入、Spring 配置、实体类序列化及 JUnit 测试等内容。

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

上次已经学会通过在命令行的模式下使用redis,由于工作需求需要给 spring mvc 换缓存,ehcache 换成redis缓存。话不多说,下面是一些工作中的总结 
引入spring 包以及junit
redis包  jedis-2.8.0.jar
        spring-data-redis-1.7.2.RELEASE.jar

spring 配置

    <context:component-scan base-package="com.test.cache" />

    <cache:annotation-driven />
        <!--序列化方式-->
    <bean id="jdkSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
    <bean id="stringSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>

    <cache:annotation-driven cache-manager="cacheManager" />
    <!--工厂-->
    <bean id="connectionFactory"
    class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="localhost" />
        <!--数据库编号 默认为 0  配置文件中默认总共为16个-->
        <property name="port" value="6379" />
        <property name="database" value="8" />
        <property name="usePool" value="true" />
        <!-- <property name="password" value="123456" /> 如果redis配置文件中设置了密码就需要添加这个 -->
        <property name="timeout" value="100" />
        <!--链接池-->
        <!-- <property name="poolConfig" ref="poolConfig" /> -->
    </bean>
    <!--模板-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory" />
        <property name="defaultSerializer" ref="jdkSerializer" />
        <property name="keySerializer" ref="stringSerializer" />
        <!-- <property name="valueSerializer" ref="stringSerializer" />
        <!--是否开启事务-->
        <!--<property name="enableTransactionSupport" value="true" />-->
    </bean>
    <!--spring缓存配置-->
    <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg ref="redisTemplate" />
        <!--缓存默认时间-->
        <property name="defaultExpiration" value="1000" />
        <!--是否开启前缀-->
        <property name="usePrefix" value="true" />
        <!--缓存时间-->
        <property name="expires">
            <map>
                <entry key="messageCache" value="30"></entry>
            </map>
        </property>
    </bean>

测试代码

    public interface CacheDao{
        String getMessage(String name);
        Person get(Person person);
}
@Service( "helloService" )
public class Cache implements CacheDao{
    @Override
    /*@Transactional*/
    @Cacheable( value = "messageCache", key = "#name" )
    public String getMessage( String name ) {
        return "Hello" + name + "!";
    }
    @Override
        @Cacheable(value="people",key="#person.id")
        public Person get(Person person){
            System.out.println("hello");
            return person;
        }
}

以上通过spring就是配置和缓存中的基本操纵 
    service中的 value="messageCache"会通过 配置中的 expires map来设置缓存存在时间,
    即跟ehcache的ehcache.xml文件有些类似,这样方便我们对缓存的管理
junit 代码

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration( locations = "classpath:applicationContext.xml" )
public class JunitTest{
    @Resource( name = "helloService" )
    private CacheDao cacheDao;
    @Test
    public void test( ) {
        cacheDao.getMessage( "a" );
        cacheDao.getMessage( "b" );
    }
}

运行结果
运行结果

其中@Cacheable( value = "messageCache", key = "#name" )的key会制定具体名称

测试实体类缓存

    @Test
    public void test( ) {

        Person person = new Person( );
        person.setId( "8" );
        person.setUserName( "Toney" );
        person.setAge( "10" );

        Cat cat = new Cat( );
        cat.setId( "1" );
        cat.setName( "Tom" );
        person.setCat( cat );

        List< String > list = new ArrayList< String >( );
        list.add( "a" );
        list.add( "b" );
        person.setList( list );

        Map< String, Object > map = new HashMap< String, Object >( );
        map.put( "打酱油", "李白" );
        map.put( "起床不刷牙", "杜甫" );
        person.setMap( map );

        Set< String > set = new HashSet< String >( );
        set.add( "阿基米德" );
        set.add( "爱英斯坦" );
        person.setSet( set );
        cacheDao.get(person );
    }

测试复合类

以上可以发现上面的messageCache信息已经过期 其中Person的内容为一些序列化信息,是因为配置文件中设置默认的 defaultSerializer 为jdkSerializer 
在保存实体类时,实体类必须实现序列化接口 Serializable
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值