1. 程式人生 > >Spring+Redis+MyBatis實現快取整合

Spring+Redis+MyBatis實現快取整合

        <!--redis快取-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId
>
org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.3</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId
>
<version>2.9.0</version> </dependency>
    <!--配置redis連線的配置檔案,placeholder的例項只能存在一個-->
    <!--<context:property-placeholder location="classpath:redis.properties"/>-->
    <!--啟用快取註解-->
    <cache:annotation-driven cache-manager="cacheManager"
/>
<!--快取管理器--> <bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager"> <property name="caches"> <set> <!--自定義的redis快取操作實現--> <bean class="com.common.cache.redis.RedisCache"> <property name="name" value="myCache"/> <property name="redisTemplate" ref="redisTemplate"/> </bean> </set> </property> </bean> <!--redis連線池配置--> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}"/> <property name="maxTotal" value="${redis.maxTotal}"/> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> </bean> <!--redis連線工廠配置--> <bean id="connectionFactory" 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="poolConfig" ref="poolConfig"/> <property name="usePool" value="true"/> </bean> <!--redis操作模板--> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="connectionFactory"/> </bean>

/**
 * Cache adapter for Redis.
 */
public class RedisCache implements Cache {
    private RedisTemplate<String, Object> redisTemplate;
    private String name;

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

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

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

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

    /**
     * 從快取中獲取key
     */
    @Override
    public ValueWrapper get(Object key) {
        final String keyf = key.toString();
        Object object;
        object = redisTemplate.execute((RedisCallback<Object>) connection -> {
            byte[] key1 = keyf.getBytes();
            byte[] value = connection.get(key1);
            if (value == null) {
                return null;
            }
            return SerializationUtils.deserialize(value);
        });
        return (object != null ? new SimpleValueWrapper(object) : null);
    }

    /**
     * 將一個新的key儲存到快取中
     * 先拿到需要快取key名稱和物件,然後將其轉成ByteArray
     */
    @Override
    public void put(Object key, Object value) {
        final String keyf = key.toString();
        final Object valuef = value;
        final long liveTime = 86400;
        redisTemplate.execute((RedisCallback<Long>) connection -> {
            byte[] keyb = keyf.getBytes();
            byte[] valueb = SerializationUtils.serialize(valuef);
            connection.set(keyb, valueb);
            if (liveTime > 0) {
                connection.expire(keyb, liveTime);
            }
            return 1L;
        });
    }


    /**
     * 刪除key
     */
    @Override
    public void evict(Object key) {
        final String keyf = key.toString();
        redisTemplate.execute((RedisCallback<Long>) connection -> connection.del(keyf.getBytes()));
    }

    /**
     * 清空key
     */
    @Override
    public void clear() {
        redisTemplate.execute((RedisCallback<String>) connection -> {
            connection.flushDb();
            return "ok";
        });
    }

    @Override
    public <T> T get(Object key, Class<T> type) {
        return null;
    }

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

    @Override
    public ValueWrapper putIfAbsent(Object key, Object value) {
        return null;
    }
}
    //在Service層寫註解
    @Cacheable(value = "myCache", key = "getMethodName()")