Java连接Redis

在 Java 程序中使用 Redis 之前,需要确保在机器上安装了 Redis 的 Java 驱动程序和 Java 环境。可以先在将 Java 电脑上并配置好环境。

安装

现在,让我们看看如何设置 Redis Java 驱动程序。

Java 连接到 Redis 服务器

请参考以下一个简单的示例代码

import redis.clients.jedis.Jedis; 

public class RedisJava {
public static void main(String[] args) {
//Connecting to Redis server on localhost
Jedis jedis = new Jedis("localhost");
System.out.println(
"Connection to server sucessfully");
//check whether server is running or not
System.out.println("Server is running:"+jedis.ping());
}
}

现在,编译并运行上面的程序来测试与 Redis 服务器的连接。可以根据需要更改路径。假设jedis.jar的当前版本在当前路径中可以使用。 执行上面代码,将生成以下结果 -

$javac RedisJava.java 
$java RedisJava 
Connection to server sucessfully 
Server is running: PONG

Redis Java 字符串示例

import redis.clients.jedis.Jedis; 

public class RedisStringJava {
public static void main(String[] args) {
//Connecting to Redis server on localhost
Jedis jedis = new Jedis("localhost");
System.out.println("Connection to server sucessfully");
//set the data in redis string
jedis.set("tutorial-name", "Redis tutorial");
// Get the stored data and print it
System.out.println("Stored string in redis::"+ jedis.get("tutorialname"));
}
}

执行上面代码,将生成以下结果 -

$javac RedisStringJava.java 
$java RedisStringJava 
Connection to server sucessfully 
Stored string in redis:: Redis tutorial

Redis Java 列表示例

import redis.clients.jedis.Jedis; 

public class RedisListJava {
public static void main(String[] args) {
//Connecting to Redis server on localhost
Jedis jedis = new Jedis("localhost");
System.out.println("Connection to server sucessfully");

  <span class="hljs-comment">//store data in redis list </span>
  jedis.lpush(<span class="hljs-string">"tutorial-list"</span>, <span class="hljs-string">"Redis"</span>); 
  jedis.lpush(<span class="hljs-string">"tutorial-list"</span>, <span class="hljs-string">"Mongodb"</span>); 
  jedis.lpush(<span class="hljs-string">"tutorial-list"</span>, <span class="hljs-string">"Mysql"</span>); 
  <span class="hljs-comment">// Get the stored data and print it </span>
  List&lt;String&gt; list = jedis.lrange(<span class="hljs-string">"tutorial-list"</span>, <span class="hljs-number">0</span> ,<span class="hljs-number">5</span>); 

  <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i&lt;list.size(); i++) { 
     System.out.println(<span class="hljs-string">"Stored string in redis:: "</span>+list.get(i)); 
  } 

}
}

执行上面代码,将生成以下结果 -

 
$javac RedisListJava.java 
$java RedisListJava 
Connection to server sucessfully 
Stored string in redis:: Redis 
Stored string in redis:: Mongodb 
Stored string in redis:: Mysql
import redis.clients.jedis.Jedis; 

public class RedisKeyJava {
public static void main(String[] args) {
//Connecting to Redis server on localhost
Jedis jedis = new Jedis("localhost");
System.out.println("Connection to server sucessfully");
//store data in redis list
// Get the stored data and print it
List<String> list = jedis.keys("*");

  <span class="hljs-keyword">for</span>(<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i&lt;list.size(); i++) { 
     System.out.println(<span class="hljs-string">"List of stored keys:: "</span>+list.get(i)); 
  } 

}
}

执行上面代码,将生成以下结果 -

$javac RedisKeyJava.java 
$java RedisKeyJava 
Connection to server sucessfully 
List of stored keys:: tutorial-name 
List of stored keys:: tutorial-list

设置 redis 服务器连接对象
 /**
  * redisCoonection
  */

 @Bean(name = "shiroConnFactiory")
 public JedisConnectionFactory connectionFactory() {
  JedisConnectionFactory conn = new JedisConnectionFactory();
  conn.setDatabase(redisDatabase);
  conn.setHostName(redisHost);
  conn.setPassword(redisPassword);
  conn.setPort(redisPort);
  conn.setTimeout(redisTimeout);
  return conn;
 }

 /**
  * redisTemplate
  */

 @Bean(name = "redisTemplate")
 public RedisTemplate<byte[], Object> redisTemplate() {
  RedisTemplate<byte[], Object> template = new RedisTemplate<>();
  template.setConnectionFactory(connectionFactory());
  return template;
 }

 /**
  * redisCacheManager
  */

 @Bean(name = "shrioRedisCacheManager")
 @DependsOn(value = "redisTemplate")
 public ShrioRedisCacheManager redisCacheManager() {
  ShrioRedisCacheManager cacheManager = new ShrioRedisCacheManager(redisTemplate());
  return cacheManager;
 }

/**
 * 项目名:onway
 * 包名:com.pactera.commons.redis
 * 文件名:RedisUtil.java
 * 版本信息:1.0.0
 * 日期:2016 年 12 月 7 日 - 下午 7:01:40
 * Copyright (c) 2016 Pactera 版权所有
 */

package com.pactera.commons.redis;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

/**

  • 类名称:RedisUtil

  • 类描述:redicache 工具类

  • 创建人:lee

  • 创建时间:2016 年 12 月 7 日 下午 7:01:40

  • @version 1.0.0
    */
    @Component
    public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    /**

    • 批量删除对应的 value
    • @param keys
      */
      public void remove(final String... keys) {
      for (String key : keys) {
      remove(key);
      }
      }

    /**

    • 批量删除 key
    • @param pattern
      */
      public void removePattern(final String pattern) {
      Set
      <Serializable> keys = redisTemplate.keys(pattern);
      if (keys.size() > 0)
      redisTemplate.delete(keys);
      }

    /**

    • 删除对应的 value
    • @param key
      */
      public void remove(final String key) {
      if (exists(key)) {
      redisTemplate.delete(key);
      }
      }

    /**

    • 判断缓存中是否有对应的 value
    • @param key
    • @return
      */
      public boolean exists(final String key) {
      return redisTemplate.hasKey(key);
      }

    /**

    • 读取缓存
    • @param key
    • @return
      */
      public Object get(final String key) {
      Object result
      = null;
      ValueOperations
      <Serializable, Object> operations = redisTemplate.opsForValue();
      result
      = operations.get(key);
      return result;
      }

    /**

    • 写入缓存
    • @param key
    • @param value
    • @return
      */
      public boolean set(final String key, Object value) {
      boolean result = false;
      try {
      ValueOperations
      <Serializable, Object> operations = redisTemplate.opsForValue();
      operations.set(key, value);
      result
      = true;
      }
      catch (Exception e) {
      e.printStackTrace();
      }
      return result;
      }

    /**

    • 写入缓存
    • @param key
    • @param value
    • @return
      */
      public boolean set(final String key, Object value, Long expireTime) {
      boolean result = false;
      try {
      ValueOperations
      <Serializable, Object> operations = redisTemplate.opsForValue();
      operations.set(key, value);
      redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
      result
      = true;
      }
      catch (Exception e) {
      e.printStackTrace();
      }
      return result;
      }
      }

 

/**
 * 项目名:onway
 * 包名:com.pactera.commons.redis
 * 文件名:RedisConfig.java
 * 版本信息:1.0.0
 * 日期:2016 年 12 月 7 日 - 下午 6:57:43
 * Copyright (c) 2016 Pactera 版权所有
 */

package com.pactera.commons.redis;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

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.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

/**

  • 类名称:RedisConfig

  • 类描述:redis 缓存管理

  • 创建人:lee

  • 创建时间:2016 年 12 月 7 日 下午 6:57:43

  • @version 1.0.0
    */
    @Configuration
    @EnableCaching
    public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public KeyGenerator wiselyKeyGenerator(){
    return new KeyGenerator() {
    @Override
    public Object generate(Object target, Method method, Object... params) {
    StringBuilder sb
    = new StringBuilder();
    sb.append(target.getClass().getName());
    sb.append(method.getName());
    for (Object obj : params) {
    sb.append(obj.toString());
    }
    return sb.toString();
    }
    };

    }

    @Bean(name = "springCM")
    public CacheManager cacheManager(@SuppressWarnings("rawtypes")RedisTemplate redisTemplate) {
    return new RedisCacheManager(redisTemplate);
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    StringRedisTemplate template
    = new StringRedisTemplate(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer
    = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om
    = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    return template;
    }
    }

 

/**
 * 项目名:onway
 * 包名:com.pactera.commons.redis
 * 文件名:RedisSessionDAO.java
 * 版本信息:1.0.0
 * 日期:2016 年 11 月 29 日 - 下午 3:11:50
 * Copyright (c) 2016 Pactera 版权所有
 */

package com.pactera.commons.redis;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import com.pactera.commons.utils.SerializeUtils;

/**

  • 类名称:RedisSessionDAO
  • 类描述:
  • 创建人:heliang
  • 创建时间:2016 年 11 月 29 日 下午 3:11:50
  • @version 1.0.0
  • @param <V>
    */

public class RedisSessionDAO<V> extends AbstractSessionDAO {
private Logger logger = LogManager.getLogger(getClass());
private RedisTemplate<byte[], V> redisTemplate;

</span><span style="color: rgba(0, 0, 255, 1)">public</span> RedisSessionDAO(RedisTemplate&lt;<span style="color: rgba(0, 0, 255, 1)">byte</span>[], V&gt;<span style="color: rgba(0, 0, 0, 1)"> redisTemplate) {
    </span><span style="color: rgba(0, 0, 255, 1)">super</span><span style="color: rgba(0, 0, 0, 1)">();
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.redisTemplate =<span style="color: rgba(0, 0, 0, 1)">  redisTemplate;
}

@Value(</span>"${shiro.expired}"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">private</span> Integer expired = 18000000<span style="color: rgba(0, 0, 0, 1)">;


</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> Integer getExpired() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> expired;
}


</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setExpired(Integer expired) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.expired =<span style="color: rgba(0, 0, 0, 1)"> expired;
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> update(Session session) <span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> UnknownSessionException {
    logger.debug(</span>"update Session:" +<span style="color: rgba(0, 0, 0, 1)"> session.getId());
    </span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.saveSession(session);

}

@SuppressWarnings(</span>"unchecked"<span style="color: rgba(0, 0, 0, 1)">)
</span><span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> saveSession(Session session) {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (session == <span style="color: rgba(0, 0, 255, 1)">null</span> || session.getId() == <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        logger.error(</span>"session or session id is null"<span style="color: rgba(0, 0, 0, 1)">);
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)">;
    }

    </span><span style="color: rgba(0, 0, 255, 1)">byte</span>[] key =<span style="color: rgba(0, 0, 0, 1)"> getByteKey(session.getId());
    session.setTimeout(expired);
    logger.debug(</span>"Save Session:" +<span style="color: rgba(0, 0, 0, 1)"> session.getId());
    redisTemplate.opsForValue().set(key, (V) session);
}

</span><span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">byte</span><span style="color: rgba(0, 0, 0, 1)">[] getByteKey(Serializable sessionId) {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (sessionId <span style="color: rgba(0, 0, 255, 1)">instanceof</span><span style="color: rgba(0, 0, 0, 1)"> String) {
        String preKey </span>= ShrioRedisCache.prefix +<span style="color: rgba(0, 0, 0, 1)"> sessionId;
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> preKey.getBytes();
    } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> SerializeUtils.serialize(sessionId);
    }
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> delete(Session session) {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (session == <span style="color: rgba(0, 0, 255, 1)">null</span> || session.getId() == <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        logger.error(</span>"session or session id is null"<span style="color: rgba(0, 0, 0, 1)">);
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)">;
    }
    logger.debug(</span>"delete Session:" +<span style="color: rgba(0, 0, 0, 1)"> session.getId());
    redisTemplate.delete(getByteKey(session.getId()));
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> Collection&lt;Session&gt;<span style="color: rgba(0, 0, 0, 1)"> getActiveSessions() {
    Set</span>&lt;Session&gt; sessions = <span style="color: rgba(0, 0, 255, 1)">new</span> HashSet&lt;Session&gt;<span style="color: rgba(0, 0, 0, 1)">();
    Set</span>&lt;<span style="color: rgba(0, 0, 255, 1)">byte</span>[]&gt; keys = redisTemplate.keys(getByteKey(ShrioRedisCache.prefix + "*"<span style="color: rgba(0, 0, 0, 1)">));
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (keys != <span style="color: rgba(0, 0, 255, 1)">null</span> &amp;&amp; keys.size() &gt; 0<span style="color: rgba(0, 0, 0, 1)">) {
        </span><span style="color: rgba(0, 0, 255, 1)">for</span> (<span style="color: rgba(0, 0, 255, 1)">byte</span><span style="color: rgba(0, 0, 0, 1)">[] key : keys) {
            Session s </span>=<span style="color: rgba(0, 0, 0, 1)"> (Session) redisTemplate.opsForValue().get(key);
            sessions.add(s);
        }
    }

    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sessions;
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">protected</span><span style="color: rgba(0, 0, 0, 1)"> Serializable doCreate(Session session) {
    logger.debug(</span>"Session create :" +<span style="color: rgba(0, 0, 0, 1)"> session.getId());
    Serializable sessionId </span>= <span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.generateSessionId(session);
    </span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.assignSessionId(session, sessionId);
    </span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">.saveSession(session);
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> sessionId;
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">protected</span><span style="color: rgba(0, 0, 0, 1)"> Session doReadSession(Serializable sessionId) {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (sessionId == <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        logger.error(</span>"session id is null"<span style="color: rgba(0, 0, 0, 1)">);
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    }
    logger.debug(</span>"Session doReadSession :" +<span style="color: rgba(0, 0, 0, 1)"> sessionId);
    </span><span style="color: rgba(0, 0, 255, 1)">byte</span>[] key =<span style="color: rgba(0, 0, 0, 1)"> getByteKey(sessionId);
    Session s </span>=<span style="color: rgba(0, 0, 0, 1)"> (Session) redisTemplate.opsForValue().get(key);
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> s;
}

}

 

/**
 * 项目名:onway
 * 包名:com.pactera.commons.redis
 * 文件名:ShrioRedisCache.java
 * 版本信息:1.0.0
 * 日期:2016 年 11 月 28 日 - 下午 3:06:06
 * Copyright (c) 2016 Pactera 版权所有
 */

package com.pactera.commons.redis;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import com.google.common.collect.Sets;
import com.pactera.commons.utils.SerializeUtils;

public class ShrioRedisCache<K, V> implements Cache<K, V> {
private Logger logger = LogManager.getLogger(getClass());
private RedisTemplate<byte[], V> redisTemplate;
public static String prefix = "shiro_redis:";

</span><span style="color: rgba(0, 0, 255, 1)">public</span> ShrioRedisCache(RedisTemplate&lt;<span style="color: rgba(0, 0, 255, 1)">byte</span>[], V&gt;<span style="color: rgba(0, 0, 0, 1)"> redisTemplate) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.redisTemplate =<span style="color: rgba(0, 0, 0, 1)"> redisTemplate;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> ShrioRedisCache(RedisTemplate&lt;<span style="color: rgba(0, 0, 255, 1)">byte</span>[], V&gt;<span style="color: rgba(0, 0, 0, 1)"> redisTemplate, String prefix) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span><span style="color: rgba(0, 0, 0, 1)">(redisTemplate);
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.prefix =<span style="color: rgba(0, 0, 0, 1)"> prefix;
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> V get(K key) <span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> CacheException {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (logger.isDebugEnabled()) {
        logger.debug(</span>"Key: {}"<span style="color: rgba(0, 0, 0, 1)">, key);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (key == <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    }

    </span><span style="color: rgba(0, 0, 255, 1)">byte</span>[] bkey =<span style="color: rgba(0, 0, 0, 1)"> getByteKey(key);
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> redisTemplate.opsForValue().get(bkey);
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> V put(K key, V value) <span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> CacheException {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (logger.isDebugEnabled()) {
        logger.debug(</span>"Key: {}, value: {}"<span style="color: rgba(0, 0, 0, 1)">, key, value);
    }

    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (key == <span style="color: rgba(0, 0, 255, 1)">null</span> || value == <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    }

    </span><span style="color: rgba(0, 0, 255, 1)">byte</span>[] bkey =<span style="color: rgba(0, 0, 0, 1)"> getByteKey(key);
    redisTemplate.opsForValue().set(bkey, value);
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> value;
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> V remove(K key) <span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> CacheException {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (logger.isDebugEnabled()) {
        logger.debug(</span>"Key: {}"<span style="color: rgba(0, 0, 0, 1)">, key);
    }

    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (key == <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">) {
        </span><span style="color: rgba(0, 0, 255, 1)">return</span> <span style="color: rgba(0, 0, 255, 1)">null</span><span style="color: rgba(0, 0, 0, 1)">;
    }

    </span><span style="color: rgba(0, 0, 255, 1)">byte</span>[] bkey =<span style="color: rgba(0, 0, 0, 1)"> getByteKey(key);
    ValueOperations</span>&lt;<span style="color: rgba(0, 0, 255, 1)">byte</span>[], V&gt; vo =<span style="color: rgba(0, 0, 0, 1)"> redisTemplate.opsForValue();
    V value </span>=<span style="color: rgba(0, 0, 0, 1)"> vo.get(bkey);
    redisTemplate.delete(bkey);
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> value;
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span> clear() <span style="color: rgba(0, 0, 255, 1)">throws</span><span style="color: rgba(0, 0, 0, 1)"> CacheException {
    redisTemplate.getConnectionFactory().getConnection().flushDb();
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">int</span><span style="color: rgba(0, 0, 0, 1)"> size() {
    Long len </span>=<span style="color: rgba(0, 0, 0, 1)"> redisTemplate.getConnectionFactory().getConnection().dbSize();
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> len.intValue();
}

@SuppressWarnings(</span>"unchecked"<span style="color: rgba(0, 0, 0, 1)">)
@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> Set&lt;K&gt;<span style="color: rgba(0, 0, 0, 1)"> keys() {
    </span><span style="color: rgba(0, 0, 255, 1)">byte</span>[] bkey = (prefix + "*"<span style="color: rgba(0, 0, 0, 1)">).getBytes();
    Set</span>&lt;<span style="color: rgba(0, 0, 255, 1)">byte</span>[]&gt; set =<span style="color: rgba(0, 0, 0, 1)"> redisTemplate.keys(bkey);
    Set</span>&lt;K&gt; result =<span style="color: rgba(0, 0, 0, 1)"> Sets.newHashSet();

    </span><span style="color: rgba(0, 0, 255, 1)">if</span><span style="color: rgba(0, 0, 0, 1)"> (CollectionUtils.isEmpty(set)) {
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> Collections.emptySet();
    }

    </span><span style="color: rgba(0, 0, 255, 1)">for</span> (<span style="color: rgba(0, 0, 255, 1)">byte</span><span style="color: rgba(0, 0, 0, 1)">[] key : set) {
        result.add((K) key);
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> result;
}

@Override
</span><span style="color: rgba(0, 0, 255, 1)">public</span> Collection&lt;V&gt;<span style="color: rgba(0, 0, 0, 1)"> values() {
    Set</span>&lt;K&gt; keys =<span style="color: rgba(0, 0, 0, 1)"> keys();
    List</span>&lt;V&gt; values = <span style="color: rgba(0, 0, 255, 1)">new</span> ArrayList&lt;&gt;<span style="color: rgba(0, 0, 0, 1)">(keys.size());
    </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (K k : keys) {
        </span><span style="color: rgba(0, 0, 255, 1)">byte</span>[] bkey =<span style="color: rgba(0, 0, 0, 1)"> getByteKey(k);
        values.add(redisTemplate.opsForValue().get(bkey));
    }
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> values;
}

</span><span style="color: rgba(0, 0, 255, 1)">private</span> <span style="color: rgba(0, 0, 255, 1)">byte</span><span style="color: rgba(0, 0, 0, 1)">[] getByteKey(K key) {
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (key <span style="color: rgba(0, 0, 255, 1)">instanceof</span><span style="color: rgba(0, 0, 0, 1)"> String) {
        String preKey </span>= <span style="color: rgba(0, 0, 255, 1)">this</span>.prefix +<span style="color: rgba(0, 0, 0, 1)"> key;
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> preKey.getBytes();
    } </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)"> {
        </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> SerializeUtils.serialize(key);
    }
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String getPrefix() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> prefix;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> setPrefix(String prefix) {
    </span><span style="color: rgba(0, 0, 255, 1)">this</span>.prefix =<span style="color: rgba(0, 0, 0, 1)"> prefix;
}

}

 

/**
 * 项目名:onway
 * 包名:com.pactera.commons.redis
 * 文件名:ShrioRedisCacheManager.java
 * 版本信息:1.0.0
 * 日期:2016 年 11 月 28 日 - 下午 3:15:04
 * Copyright (c) 2016 Pactera 版权所有
 */

package com.pactera.commons.redis;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.cache.AbstractCacheManager;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;

/**

  • 类名称:ShrioRedisCacheManager

  • 类描述:

  • 创建人:heliang

  • 创建时间:2016 年 11 月 28 日 下午 3:15:04

  • @version 1.0.0
    */
    public class ShrioRedisCacheManager extends AbstractCacheManager {
    private Logger logger = LogManager.getLogger(getClass());
    private RedisTemplate<byte[], Object> redisTemplate;

    public ShrioRedisCacheManager(RedisTemplate<byte[], Object> redisTemplate) {
    this.redisTemplate = redisTemplate;
    }

    @Override
    protected Cache<byte[], Object> createCache(String name) throws CacheException {
    return new ShrioRedisCache<byte[], Object>(redisTemplate, name);
    }

}