美文网首页
spring-redis缓存

spring-redis缓存

作者: ythmilk | 来源:发表于2018-07-04 10:32 被阅读52次

pom.xml中添加

    <!-- Redis客户端 -->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.9.0</version>
    </dependency>
    <!-- redis Spring 基于注解配置 -->
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>1.7.2.RELEASE</version>
    </dependency>

redis.properties文件

#JedisPoolConfig的参数
#最大连接数
redis.pool.maxTotal=30
#最大空闲时间
redis.pool.maxIdle=10
#每次最大连接数
redis.pool.numTestsPerEvictionRun=1024
#释放扫描的扫描间隔
redis.pool.timeBetweenEvictionRunsMillis=30000
#连接的最小空闲时间
redis.pool.minEvictableIdleTimeMillis=1800000
#连接控歘按时间多久后释放,当空闲时间>该值且空闲连接>最大空闲连接数时直接释放
redis.pool.softMinEvictableIdleTimeMillis=10000
#获得链接时的最大等待毫秒数,小于0:阻塞不确定时间,默认-1
redis.pool.maxWaitMillis=1500
#在获得链接的时候检查有效性,默认false
redis.pool.testOnBorrow=true
#在空闲时检查有效性,默认false
redis.pool.testWhileIdle=true
#连接耗尽时是否阻塞,false报异常,true阻塞超时,默认true
redis.pool.blockWhenExhausted=false

#JedisConnectionFactory的参数
#主机地址,默认:localhost
redis.hostName=localhost
#主机端口,默认:6379
redis.port=6379
#超时时间,默认:2000
redis.timeout=3000
#密码
#redis.password
#是否使用连接池,默认true
redis.usePool=true
#使用数据库的索引,0-15之间的数字,默认:0
redis.dbIndex=0
#是否使用数据类型的转换,默认:true
#redis.convertPipelineAndTxResults
#哨兵配置
#redis.sentinelConfig
#集群配置
#redis.clusterConfig

redis-spring.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:cache="http://www.springframework.org/schema/cache"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/cache
                        http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">
    <!--引入配置文件-->
    <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="order" value="1"/>
        <property name="ignoreUnresolvablePlaceholders" value="true"/>
        <property name="locations">
            <list>
                <value>classpath:redis.properties</value>
            </list>
        </property>
    </bean>

    <cache:annotation-driven  cache-manager="cacheManager"/>
    <!--配置 jedis pool-->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!-- 最大连接数 -->
        <property name="maxTotal" value="${redis.pool.maxTotal}"/>
        <!-- 最大空闲时间 -->
        <property name="maxIdle" value="${redis.pool.maxIdle}"/>
        <!-- 每次最大连接数 -->
        <property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"/>
        <!-- 释放扫描的扫描间隔 -->
        <property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"/>
        <!-- 连接的最小空闲时间 -->
        <property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"/>
        <!-- 连接控歘按时间多久后释放,当空闲时间>该值且空闲连接>最大空闲连接数时直接释放 -->
        <property name="softMinEvictableIdleTimeMillis" value="${redis.pool.softMinEvictableIdleTimeMillis}"/>
        <!-- 获得链接时的最大等待毫秒数,小于0:阻塞不确定时间,默认-1 -->
        <property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}"/>
        <!-- 在获得链接的时候检查有效性,默认false -->
        <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
        <!-- 在空闲时检查有效性,默认false -->
        <property name="testWhileIdle" value="${redis.pool.testWhileIdle}"/>
        <!-- 连接耗尽时是否阻塞,false报异常,true阻塞超时 默认:true-->
        <property name="blockWhenExhausted" value="${redis.pool.blockWhenExhausted}"/>
    </bean>
    <!--spring data redis -->
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <property name="hostName" value="${redis.hostName}"/>
        <property name="port" value="${redis.port}"/>
        <property name="timeout" value="${redis.timeout}"/>
        <property name="database" value="${redis.dbIndex}"/>
        <property name="usePool" value="${redis.usePool}"/>
        <!--可以通过构造注入或者Set注入两种方式-->
        <property name="poolConfig" ref="jedisPoolConfig"/>
    </bean>

    <!--redisTemplate-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
        <!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!!  -->
        <property name="keySerializer" >
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
        </property>
        <property name="valueSerializer" >
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
        </property>
        <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="hashValueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>
        <!--开启事务  -->
        <property name="enableTransactionSupport" value="true"></property>
    </bean>
    <!--自定义redis工具类,在需要缓存的地方注入此类  -->
    <bean id="redisUtil" class="com.yth.common.util.RedisUtil">
        <property name="redisTemplate" ref="redisTemplate" />
    </bean>
    <!--支持Spring注解缓存-->

    <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
        <property name="caches">
            <set>
                <bean class="org.springframework.data.redis.cache.RedisCache">
                    <constructor-arg name="redisOperations" ref="redisTemplate"/>
                    <constructor-arg name="name" value="common"/>
                    <constructor-arg name="prefix" value=""/>
                    <constructor-arg name="expiration" value="6400" />
                </bean>

                <bean class="com.yth.common.util.cache.RedisCache">
                    <property name="redisTemplate" ref="redisTemplate" />
                    <property name="name" value="common"/>
                    <!-- common名称要在类或方法的注解中使用 -->
                </bean>
            </set>
        </property>
    </bean>
</beans>

redis-spring.xml文件引入spring-mvc.xml文件中,引入另一个配置文件中不起作用。

RedisCache

package com.yth.common.util.cache;

import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.SerializationUtils;

import java.io.*;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 
 * @Date: 2018/7/3 15:06
 */
public class RedisCache implements Cache {
    private RedisTemplate<String, Object> redisTemplate;
    private String name;

    @Override
    public void clear() {
        System.out.println("-------緩存清理------");
        redisTemplate.execute(new RedisCallback<String>() {
            @Override
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushDb();
                return "ok";
            }
        });
    }

    @Override
    public void evict(Object key) {
        System.out.println("-------緩存刪除------");
        final String keyf=key.toString();
        redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.del(keyf.getBytes());
            }

        });

    }

    @Override
    public ValueWrapper get(Object key) {
        System.out.println("------缓存获取-------"+key.toString());
        final String keyf = key.toString();
        Object object = null;
        object = redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] key = keyf.getBytes();
                byte[] value = connection.get(key);
                if (value == null) {
                    System.out.println("------缓存不存在-------");
                    return null;
                }
                return SerializationUtils.deserialize(value);
            }
        });
        ValueWrapper obj=(object != null ? new SimpleValueWrapper(object) : null);
        System.out.println("------获取到内容-------"+obj);
        return  obj;
    }

    @Override
    public void put(Object key, Object value) {
        System.out.println("-------加入缓存------");
        System.out.println("key----:"+key);
        System.out.println("key----:"+value);
        final String keyString = key.toString();
        final Object valuef = value;
        final long liveTime = 86400;
      //  redisTemplate.opsForValue().set(key.toString(), value, liveTime, TimeUnit.SECONDS);
        redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                byte[] keyb = keyString.getBytes();
                byte[] valueb = SerializationUtils.serialize((Serializable) valuef);
                connection.set(keyb, valueb);
                if (liveTime > 0) {
                    connection.expire(keyb, liveTime);
                }
                return 1L;
            }
        });

    }

    @Override
    public <T> T get(Object arg0, Class<T> arg1) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <T> T get(Object o, Callable<T> callable) {
        return null;
    }

    @Override
    public String getName() {
        return this.name;
    }

    @Override
    public Object getNativeCache() {
        return this.redisTemplate;
    }

    @Override
    public ValueWrapper putIfAbsent(Object arg0, Object arg1) {
        // TODO Auto-generated method stub
        return null;
    }

    public RedisTemplate<String, Object> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

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

}

目前这样存入的乱码,但缓存读取是ok的,懵逼~~~。

在service层添加缓存注解(在实现类的方法上)

@Cacheable(value="common",key="'getUserById_'+#id")

相关文章

网友评论

      本文标题:spring-redis缓存

      本文链接:https://www.haomeiwen.com/subject/faasuftx.html