spring-data-redis Spring 整合 redis 做 cache xml实现

Spring整合redis做缓存

1. 导包
<!-- redis架包 -->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.6.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

<!-- jackson炸包 -->
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- log炸包 -->
<!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2. redis.properties文件
#============================#
#==== Redis settings ====#
#============================#
#redis 服务器 IP
redis.host=127.0.0.1
#redis 服务器端口
redis.port=6379
#redis 密码
redis.pass=
#redis 支持16个数据库(相当于不同用户)可以使不同的应用程序数据彼此分开同时又存储在相同的实例上
redis.dbIndex=1
#redis 缓存数据过期时间单位秒
redis.expiration=3000
#控制一个 pool 最多有多少个状态为 idle 的jedis实例
redis.maxIdle=300
#控制一个 pool 可分配多少个jedis实例
redis.maxActive=600
#当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
redis.maxWait=1000
#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
redis.testOnBorrow=true
3. 配置spring-cache-redis.xml文件
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/cache
  http://www.springframework.org/schema/cache/spring-cache.xsd">
    <!-- **************************************************redis********************************************************** -->
    <!-- 配置文件加载 -->
    <context:property-placeholder location="classpath:*.properties"/>
    <!-- 配置 JedisPoolConfig 实例 -->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxTotal" value="${redis.maxActive}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
    </bean>

    <!-- 配置JedisConnectionFactory -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.host}"/>
        <property name="port" value="${redis.port}"/>
        <property name="password" value="${redis.pass}"/>
        <property name="database" value="${redis.dbIndex}"/>
        <property name="poolConfig" ref="poolConfig"/>
    </bean>

    <!-- 配置RedisTemplate -->
    <!-- redis 序列化策略 ,通常情况下key值采用String序列化策略, -->
    <!-- 如果不指定序列化策略,StringRedisTemplate的key和value都将采用String序列化策略; -->
    <!-- 但是RedisTemplate的key和value都将采用JDK序列化 这样就会出现采用不同template保存的数据不能用同一个template删除的问题 -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
          p:connectionFactory-ref="jedisConnectionFactory"
          p:keySerializer-ref="stringRedisSerializer"
          p:hashKeySerializer-ref="stringRedisSerializer"
          p:valueSerializer-ref="genericJackson2JsonRedisSerializer"
          p:hashValueSerializer-ref="genericJackson2JsonRedisSerializer"
    />
    <!--JDK序列化,速度快但占用空间较大,对象必须实现java.io.Serializable接口 -->
    <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
    <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" />
    <!-- XML序列化,速度慢空间占用较大 -->
    <!--<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller"/>
    <bean id="oxmSerializer" class="org.springframework.data.redis.serializer.OxmSerializer"
          p:marshaller-ref="jaxb2Marshaller"
          p:unmarshaller-ref="jaxb2Marshaller"/>-->
    <!-- JSON序列化,空间占用小,无需指明但对象类型
            SerializationException:
                Could not read JSON: Cannot construct instance of `com.learn.cache.model.Account` (although at least one Creator exists):
                cannot deserialize from Object value (no delegate- or property-based Creator)
            解决办法: 给实体类com.learn.cache.model.Account添加默认的构造方法 public Account(){}
    -->
    <bean id="genericJackson2JsonRedisSerializer" class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
    <!-- JSON序列化,空间占用小,需指明对象类型,不知道怎么在xml配置中注入参数类型为Class<?>的值,可在代码中指定 -->
    <!-- <bean id="jackson2JsonRedisSerializer" class="org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer"/> -->

    <!-- 配置RedisCacheManager -->
    <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
        <constructor-arg name="redisOperations" ref="redisTemplate"/>
        <property name="defaultExpiration" value="${redis.expiration}"/>
    </bean>
    <!-- 配置RedisCacheConfig -->
    <bean id="redisCacheConfig" class="com.learn.cache.RedisCacheConfig">
        <constructor-arg ref="jedisConnectionFactory"/>
        <constructor-arg ref="redisTemplate"/>
        <constructor-arg ref="redisCacheManager"/>
    </bean>

    <!-- 开启注解扫描 -->
    <!--<context:annotation-config />-->
    <context:component-scan base-package="com.learn"/>
    <bean id="testServiceBean" class="com.learn.cache.service.TestService"/>
    <bean id="accountServiceBean" class="com.learn.cache.service.AccountService"/>
</beans>
4. 开启缓存, 并配置key生成策略
package com.learn.cache;

import java.lang.reflect.Method;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
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 RedisCacheConfig extends CachingConfigurerSupport {
    protected final static Logger log = LoggerFactory.getLogger(RedisCacheConfig.class);

    private volatile JedisConnectionFactory mJedisConnectionFactory;
    private volatile RedisTemplate<String, String> mRedisTemplate;
    private volatile RedisCacheManager mRedisCacheManager;

    public RedisCacheConfig() {
        super();
    }

    public RedisCacheConfig(JedisConnectionFactory mJedisConnectionFactory, RedisTemplate<String, String> mRedisTemplate, RedisCacheManager mRedisCacheManager) {
        super();
        this.mJedisConnectionFactory = mJedisConnectionFactory;
        this.mRedisTemplate = mRedisTemplate;
        this.mRedisCacheManager = mRedisCacheManager;
    }

    public JedisConnectionFactory redisConnectionFactory() {
        return mJedisConnectionFactory;
    }

    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
        return mRedisTemplate;
    }

    public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
        return mRedisCacheManager;
    }


    @Bean
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method,
                                   Object... params) {
                //规定  本类名+方法名+参数名 为key
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName() + "_");
                sb.append(method.getName() + "_");
                for (Object obj : params) {
                    sb.append(obj.toString() + ",");
                }
                return sb.toString();
            }
        };
    }

}
5. 编写实体类, 及cache使用方法
package com.learn.cache.model;

import java.io.Serializable;

/**
 * 首先定义一个实体类:账号类,具备基本的 id 和 name 属性,且具备 getter 和 setter 方法
 *
 * 清单 1. Account.java
 *
 * @author qq
 * @date 2018-04-27
 */
public class Account implements Serializable {
    private static final long serialVersionUID = 1L;

    private int id;
    private String name;
    private String password;

    public Account() {
        super();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Account(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
package com.learn.cache.service;

import com.learn.cache.model.Account;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

/**
 * 使用@Cacheable, @CachePut, @CacheEvict, @CacheConfig spring通过AOP对方法进行缓存管理
 * <p>
 * 实体类就是上面自定义缓存方案定义的 Account.java,这里重新定义了服务类,如下:
 * <p>
 * 清单 6. AccountService.java
 *
 * @author aa
 * @date 2018-04-27
 */
public class TestService {

    @Cacheable(value = "redis-cache-string", key = "'redis_key_' + #userName", condition = "true")
    public String getResisValue(String userName) {
        // 方法内部实现不考虑缓存逻辑,直接实现业务
        System.out.println("查询数据库..." + userName);
        return "redis_value_" + userName;
    }

//    @CacheEvict(value = "redis-cache-string", key = "'redis_key' + #userName", condition = "true", allEntries = true, beforeInvocation = true)
    @CacheEvict(value = "redis-cache-string", key = "'redis_key_' + #userName", condition = "true")
    public void delRedisValue(String userName) {
        System.out.println("删除数据库");
    }
}
package com.learn.cache.service;

import com.learn.cache.model.Account;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;

/**
 * 使用@Cacheable, @CachePut, @CacheEvict, @CacheConfig spring通过AOP对方法进行缓存管理
 * <p>
 * 实体类就是上面自定义缓存方案定义的 Account.java,这里重新定义了服务类,如下:
 * <p>
 * 清单 6. AccountService.java
 *
 * @author aa
 * @date 2018-04-27
 */
public class AccountService {

    /**
     * 使用了一个缓存名叫 accountCache
     *
     * 注意,此类的 getAccountByName 方法上有一个注释 annotation,即 @Cacheable(value=”accountCache”),
     * 这个注释的意思是,当调用这个方法的时候,会从一个名叫 accountCache 的缓存中查询,如果没有,则执行实际的方法(即查询数据库),并将执行的结果存入缓存中,否则返回缓存中的对象。
     * 这里的缓存中的 key 就是参数 userName,value 就是 Account 对象。“accountCache”缓存是在 spring*.xml 中定义的名称。
     *
     * key condition ,前面的 # 号代表这是一个 SpEL 表达式
     * @param userName
     * @return
     */
    @Cacheable(value = "accountCache", key = "'model:' + #userName", condition = "#userName.length() >= 4")
    public Account getAccountByName(String userName) {
//        Jackson2JsonRedisSerializer  json = new Jackson2JsonRedisSerializer();
        // 方法内部实现不考虑缓存逻辑,直接实现业务
        return getFromDB(userName);
    }


    @Cacheable(value = "accountCache", key = "#userName.concat(#password)")
    public Account getAccount(String userName, String password, boolean sendLog) {
        // 方法内部实现不考虑缓存逻辑,直接实现业务
        return getFromDB(userName, password);

    }

    /**
     * 好,到目前为止,我们的 spring cache 缓存程序已经运行成功了,但是还不完美,
     * 因为还缺少一个重要的缓存管理逻辑:清空缓存,当账号数据发生变更,那么必须要清空某个缓存,另外还需要定期的清空所有缓存,以保证缓存数据的可靠性。
     * 清空 accountCache 缓存
     *
     * 清单 10. AccountService.java
     * @param account
     */
//    @CacheEvict(value = "accountCache", key = "#account.getName()")
    /**
     * 更新 accountCache 缓存
     * @param account dd
     */
    @CachePut(value = "accountCache", key = "#account.getName()")
    public void updateAccount(Account account) {
        updateDB(account);
    }

    /**
     * reload 清空 accountCache 缓存
     */
    @CacheEvict(value = "accountCache", allEntries = true)
    public void reload() {
    }

    private Account getFromDB(String acctName) {
        System.out.println("real querying db..." + acctName);
        return new Account(acctName);
    }

    private Account getFromDB(String acctName, String password) {
        System.out.println("real querying db..." + acctName + "+" + password);
        return new Account(acctName);
    }

    private void updateDB(Account account) {
        System.out.println("real update db..." + account.getName());
    }

}

6. 测试字符串存储及实体类存储
package com.learn.cache;

import com.learn.cache.model.Account;
import com.learn.cache.service.AccountService;
import com.learn.cache.service.TestService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

public class Main {

    public static void main(String[] args) {
        // 加载 spring 配置文件
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-cache-redis.xml");

        RedisTemplate redisTemplate = (RedisTemplate) context.getBean("redisTemplate");

        redisTemplate.opsForValue().set("redis2", "ceshiRedis222");

        System.out.println(redisTemplate.opsForValue().get("redis2"));


        // 测试string类型缓存
//        testRedisCache(context);
//        delRedisCache(context);

        // 测试json类型缓存
        testRedisCacheModel(context);
    }

    /**
     * 测试普通村缓存
     * @param context
     */
    public static void testRedisCache(ApplicationContext context) {
        // 测试缓存
        TestService s = (TestService) context.getBean("testServiceBean");
        // 第一次查询,应该走数据库
        System.out.print("first query...");
        s.getResisValue("somebody");
        // 第二次查询,应该不查数据库,直接返回缓存的值
        System.out.print("second query...");
        s.getResisValue("somebody");
        System.out.println();
    }

    /**
     * 测试实体类缓存
     * @param context 文档
     */
    public static void testRedisCacheModel(ApplicationContext context) {
        // 测试缓存
        AccountService s = (AccountService) context.getBean("accountServiceBean");
        // 第一次查询,应该走数据库
        System.out.println("first query...");
        s.getAccountByName("somebody");
        // 第二次查询,应该不查数据库,直接返回缓存的值
        System.out.println("second query...");
        Account account = s.getAccountByName("somebody");
        System.out.println(account);
    }

    /**
     * 删除缓存
     * @param context 文档
     */
    public static void delRedisCache(ApplicationContext context) {
        // 测试缓存
        TestService s = (TestService) context.getBean("testServiceBean");
        // 第一次查询,应该走数据库
        System.out.print("first query...");
        s.getResisValue("somebody");
        // 第二次查询,应该不查数据库,直接返回缓存的值
        System.out.println("second query...");
        String jj = s.getResisValue("somebody");
        System.out.println(jj + ";second query end...");

        System.out.println("clear cache begin...");
        s.delRedisValue("somebody");
        System.out.println("three query...");
        s.getResisValue("somebody");
    }
}

报错看 https://mp.csdn.net/postedit/80170626


猜你喜欢

转载自blog.csdn.net/hkk666123/article/details/80171107