Spring基于注解整合Redis实现内容缓存

1:创建MAVNE项目准备和Spring注解方式整合Redis所需依赖包

2:在applicationContext.xml中增加Redis和Spring整合相关配置

JedisConnectionFactory 为 Jedis 连接工厂,配置由单独抽象的 JedisPoolConfig 提供。

RedisTemplate 的作用,RedisTemplate 对 RedisConnection 进行了封装。提供连接管理,序列化等功能,它对 Redis 的交互进行了更高层次的抽象,极大的方便和简化了 Redis 的操作。cacheManager 做为 redis 统一的调度和管理者

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns="http://www.springframework.org/schema/beans"

       xmlns:context="http://www.springframework.org/schema/context"

       xmlns:aop="http://www.springframework.org/schema/aop"

       xmlns:tx="http://www.springframework.org/schema/tx"

       xmlns:cache="http://www.springframework.org/schema/cache"

       xsi:schemaLocation="http://www.springframework.org/schema/beans

                                      http://www.springframework.org/schema/beans/spring-beans-4.1.xsd

                                                               http://www.springframework.org/schema/context

                                                               http://www.springframework.org/schema/context/spring-context-4.1.xsd

                                                               http://www.springframework.org/schema/aop

                                                               http://www.springframework.org/schema/aop/spring-aop-4.1.xsd

                                                               http://www.springframework.org/schema/tx

                                                               http://www.springframework.org/schema/tx/spring-tx-4.1.xsd

                                                               http://www.springframework.org/schema/cache

                                                               http://www.springframework.org/schema/cache/spring-cache.xsd">

    <!--开启注解缓存-->

    <cache:annotation-driven/>

    <!--jedispool配置-->

    <bean class="redis.clients.jedis.JedisPoolConfig" id="poolConfig">

        <!-- 最大等待时间-->

        <property name="maxWaitMillis" value="${redis.maxWait}"/>

        <!--测试连接-->

        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>

        <!-- 最大空闲数-->

        <property name="maxIdle"  value="${redis.maxIdle}"/>

        <!--最大连接数-->

        <property name="maxTotal"  value="${redis.maxTotal}"/>

    </bean>

 

    <!--配置jedis连接-->

    <bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" id="js">

        <property name="poolConfig" ref="poolConfig"/>

        <property name="hostName" value="${redis.host}"/>

        <property name="password" value="${redis.pass}"/>

        <property name="port" value="${redis.port}"/>

        <property name="database" value="${redis.dbIndex}"/>

    </bean>

 

 

    <!--配置redisTemplete-->

    <bean class="org.springframework.data.redis.core.RedisTemplate" name="redisTemplate">

        <property name="connectionFactory" ref="js"/>

       <!-- 配置key   value-->

        <property name="keySerializer">

            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>

        </property>

        <!--value-->

        <property name="valueSerializer">

            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>

        </property>

    </bean>

 <!--配置RedisCacheManager-->

    <bean class="org.springframework.data.redis.cache.RedisCacheManager" name="cacheManager">

        <!--加入RedisTemplate-->

        <constructor-arg name="redisOperations" ref="redisTemplate"/>

        <!--缓存数据的存活期-->

        <property name="defaultExpiration" value="${redis.expiration}"/>

    </bean>

 

</beans>

4:准备redis.properties

#============================#

#==== Redis settings ====#

#============================#

#redis 服务器 IP

redis.host=192.168.3.132

 

#redis 服务器端口

redis.port=6379

 

#redis 密码

redis.pass=123456

 

#redis 支持16个数据库(相当于不同用户)可以使不同的应用程序数据彼此分开同时又存储在相同的实例上

redis.dbIndex=8

 

#最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;

redis.maxWait=30000

 

#############连接池配置###############

#redis 缓存数据过期时间单位秒

redis.expiration=3000

 

#控制一个 pool 最多有多少个状态为 idle 的jedis实例

redis.maxIdle=300

 

#控制一个 pool 可分配多少个jedis实例

redis.maxActive=600

#最大连接数

redis.maxTotal=20000

 

#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;

redis.testOnBorrow=true

 

5.在Service实现类增加缓存注解标签

缓存一般使用在服务层,在你想缓存的方法上面添加相应的注解即可,下面三个缓存的注解要求掌握。

 

   @Cacheable  spring 会在其被调用后将返回值缓存起来,以保证下次利用同样的参数来执行该方法时可以直接从缓存中获取结果,而不需要再次执行该方法。

value属性指定Cache名称:value属性是必须指定的,其表示当前方法的返回值是会被缓存在哪个Cache上的,对应Cache的名称。

key属性是用来指定Spring缓存方法的返回结果时对应的key的。该属性支持SpringEL表达式。当我们没有指定该属性时,Spring将使用默认策略生成key。我们这里先来看看自定义策略,至于默认策略会在后文单独介绍。

   自定义策略是指我们可以通过Spring的EL表达式来指定我们的key。这里的EL表达式可以使用方法参数及它们对应的属性。使用方法参数时我们可以直接使用“#参数名”或者“#p参数index”

 

   @CachePut  标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。

 

   @CacheEvict 用来标注在需要清除缓存元素的方法或类上的。

value表示清除操作是发生在哪些Cache上的(对应Cache的名称)。

allEntries是boolean类型,表示是否需要清除缓存中的所有元素。

package com.ujiuye.service;

 

import com.ujiuye.bean.UserInfo;

import com.ujiuye.mapper.UserDao;

import org.springframework.cache.annotation.CacheEvict;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Service;

 

import javax.annotation.Resource;

import java.util.List;

@Service

public class UserServiceImpl  implements UserService {

    @Resource

    UserDao dao;

    @Cacheable(value = "getAllUser",key = "'getAllUser_value='")

    @Override

    public List<UserInfo> getAllUser() {

        return dao.getAll();

    }

 

    @Override

    @Cacheable(value = "getUserById",key = "'getUserById_value_uid='+#uid")

    public UserInfo getUserById(int uid) {

        return dao.getUserById(uid);

    }

 

    @Override

    @CacheEvict(value = {"getAllUser","getUserById"},allEntries = true)

    public int updateUser(UserInfo userInfo) {

        return dao.update(userInfo);

    }

 

    @Override

    @CacheEvict(value = {"getAllUser","getUserById"},allEntries = true)

    public int del(int uid) {

        return dao.del(uid);

    }

 

    @Override

    @CacheEvict(value = {"getAllUser","getUserById"},allEntries = true)

    public int add(UserInfo userInfo) {

        return dao.add(userInfo);

    }

}

原文地址:https://www.cnblogs.com/masterhxh/p/13044852.html