Redis(使用Jedis)初步使用


关于redis,网上有太多的介绍,也有使用,但是找了很多,基本都是用的spring-data-redis,而不是jedis。二者的比较可以在网上查看,个人还是先琢磨着用了jedis的实现。
提到redis,肯定会想到memcached,那就简单的介绍一下memcached。

memcached:内存对象缓存系统,能回避读取磁盘时发生的I/O消耗成本,在web应用程序和数据库之间复制粘贴memcached时会产生较好的读取性能。 常用于需要快速查询的应用程序。memcached所有的值均是字符串,而redis支持丰富的功能集,同时redis可以持久化数据。

Redis: redis远程字典服务器,开源,高级的NOSQL键值数据存储。 redis是一种内存型数据存储,也可以将它写入磁盘中实现耐久性。

redis使用两种方式来持久存储数据:RDB 和AOF 。
RDB持久性: 按照指定的间隔对数据集执行时间点快照,不是非常持久,而且可能会丢失一些数据,但是速度非常快。
AOF持久性要长得多,而且记录了服务器收到的每个写入操作,写入操作在服务器启动时重新执行,重新构建原始数据集,查询redis时,将从内存中获取数据,绝不从磁盘获取数据。

Redis支持的数据类型: 字符串,列表,集合,有序集,哈希值,速度快,操作原子性。 所以多个客户端会并发访问一个redis服务器,获取相同的更新值。

Redis多效用,1,缓存 2消息队列(redis支持发布,订阅) 3 短期应用程序数据(web回话,web页面命中计数)。

接下来记录我自己根据在网上研究的实现的一个小demo。
redis的安装网上有很多,可以自行研究安装。

环境: maven+ mybaitis+springmvc
首先jar的引用:pom.xml中

<!-- 与redis集成 -->

<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.0</version>
</dependency>

然后配置文件:redis.properties
#redis相关配置
#最大连接数,设定为8
redis.maxTotal=8
#最大空闲连接数,设定为5
redis.maxIdle=5
#最小空闲连接数,即为初始化连接数,设定为1
redis.minIdle=1
#最大等待时间单位为毫秒,设定为10秒
redis.maxWaitMillis=10000
# 对获取到的connection进行validateObject检验
redis.testOnBorrow=true
#redis域名或ip配置
redis.hostName=localhost
#redis开设的端口号
redis.port=6379


配置文件:spring-config-redis.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:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd">
 
 
 
<!-- basic jedis pool configuration -->
    <bean id="JedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
         <!-- 最大连接数限制,系统默认为8 -->
        <property name="maxTotal" value="${redis.maxTotal}" />
    <!-- 最大空闲连接数限制,系统默认为8 -->
        <property name="maxIdle" value="${redis.maxIdle}" />
    <!-- 最小空闲连接数限制,系统默认为0 -->
    <property name="minIdle" value="${redis.minIdle}" />
    <!-- 最大等待时间单位为毫秒,设定为10秒 -->
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
    <!-- 对获取到的connection进行validateObject检验-->
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />
       
      
<property name="timeBetweenEvictionRunsMillis" value="-1" />
    </bean>
   
   <!-- 这边设置各个业务的redis域名/ip以及对应的端口号 -->
    <!-- 期望将各个业务应用用到的redis隔离开,目前通过端口号隔离 -->
    <bean id="JedisPool" class="redis.clients.jedis.JedisPool"> 
         <constructor-arg index="0" ref="JedisPoolConfig" />
        <constructor-arg index="1" value="${redis.hostName}" />
        <constructor-arg index="2" value="${redis.port}" /> 
    </bean> 
   
    <!-- JedisPool manager -->
    <bean id="JedisTemplate" class="com.demo.modules.cache.jedis.JedisTemplate" >
     <constructor-arg index="0" name="jedisPool" ref="JedisPool" />
    </bean>


</beans>


JedisTemplate是另外实现的一个类。
public class JedisTemplate {
private Logger logger = LoggerFactory.getLogger(JedisTemplate.class);
@Autowired
private JedisPool jedisPool;

public JedisTemplate(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}

// 设置key并且设定一个默认失效时间
// 设置失效时间,此处单位秒seconds
public void set(String key, String value, int expiredseconds) {
if (key != null && value != null && expiredseconds > 0) {
JedisPool jedisPool = null;
Jedis jedis = null;
try {
// 获取jedis pool对象
jedisPool = getJedisPool();
if (jedisPool != null) {
// 从jedis pool连接池里边获取一个jedis连接对象
jedis = jedisPool.getResource();
jedis.setex(key, expiredseconds, value);
logger.info("jedisTemplate>>>set key={},value={},expired={} succeed", new Object[] { key, value, expiredseconds });
}
} catch (Exception e) {
if (jedisPool != null) {
jedisPool.returnBrokenResource(jedis);
}
logger.error("jedisTemplate>>>set key={},value={},expired={} failed e={}", new Object[] { key, value, expiredseconds, e.getCause() });
} finally {
// 处理完毕后,一定将jedis连接对象释放回到连接池中
if (jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
}

// 设置key-value不设置失效时间
public void set(String key, String value) {
if (key != null && value != null) {
JedisPool jedisPool = null;
Jedis jedis = null;
try {
jedisPool = getJedisPool();
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.set(key, value);
logger.info("jedisTemplate>>>set key={},value={} succeed", new Object[] { key, value });
}
} catch (Exception e) {
if (jedisPool != null) {
jedisPool.returnBrokenResource(jedis);
}
logger.error("jedisTemplate>>>set key={},value={} failed e={}", new Object[] { key, value, e.getCause() });
} finally {
if (jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
}

// 根据key查询value
public String get(String key) {
String value = "";
if (null != key && !"".equals(key)) {
JedisPool jedisPool = null;
Jedis jedis = null;
try {
jedisPool = getJedisPool();
if (jedisPool != null) {
jedis = jedisPool.getResource();
String tmp = jedis.get(key);
value = tmp != null ? tmp : value;
logger.info("jedisTemplate>>>get key={},value={} succeed", new Object[] { key, value });
}
} catch (Exception e) {
if (jedisPool != null) {
jedisPool.returnBrokenResource(jedis);
}
logger.error("jedisTemplate>>>get key={},value={} failed e={}", new Object[] { key, value, e.getCause() });
} finally {
if (jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
return value;
}

// 设置hset,key-fieldKey-value值
public void hset(String key, String fieldKey, String value) {
if (key != null && value != null && fieldKey != null) {
JedisPool jedisPool = null;
Jedis jedis = null;
try {
jedisPool = getJedisPool();
if (jedisPool != null) {
jedis = jedisPool.getResource();
jedis.hset(key, fieldKey, value);
logger.info("jedisTemplate>>>hset key={},fieldKey={},value={} succeed", new Object[] { key, fieldKey, value });
}
} catch (Exception e) {
if (jedisPool != null) {
jedisPool.returnBrokenResource(jedis);
}
logger.error("jedisTemplate>>>hset key={},fieldKey={},value={} failed e={}", new Object[] { key, fieldKey, value, e.getCause() });
} finally {
if (jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
}

// 获取hgetall key对应的值,放在map<fieldKey,value>中返回
public Map<String, String> hgetAll(String key) {
Map<String, String> map = new HashMap<String, String>();
if (key != null) {
JedisPool jedisPool = null;
Jedis jedis = null;
try {
jedisPool = getJedisPool();
if (jedisPool != null) {
jedis = jedisPool.getResource();
Map<String, String> tmpmap = jedis.hgetAll(key);
map = tmpmap != null ? tmpmap : map;
logger.info("jedisTemplate>>>hgetall key={},value={} succeed", new Object[] { key, tmpmap });
}
} catch (Exception e) {
if (jedisPool != null) {
jedisPool.returnBrokenResource(jedis);
}
logger.error("jedisTemplate>>>hget key={},value={},failed e={}", new Object[] { key, map, e.getCause() });
} finally {
if (jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
return map;
}

/**
* <pre>
* 查询匹配keys全部key键值列表
*
* redis里边的keys* 命令
*/
public Set<String> keys(String keysPattern) {
Set<String> set = new HashSet<String>();
if (keysPattern != null && !"".equals(keysPattern)) {
JedisPool jedisPool = null;
Jedis jedis = null;
try {
jedisPool = getJedisPool();
if (jedisPool != null) {
jedis = jedisPool.getResource();
Set<String> tmp = jedis.keys(keysPattern);
set = tmp != null ? tmp : set;
logger.info("jedisTemplate>>>keys keyPattern={}, set.size={}", new Object[] { keysPattern, set.size() });
}
} catch (Exception e) {
if (jedisPool != null) {
jedisPool.returnBrokenResource(jedis);
}
logger.error("jedisTemplate>>>keys keyPattern={}, failed e={}", new Object[] { keysPattern, e.getCause() });
} finally {
if (jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
return set;
}

// 从hset中hget出对应的key-field对应的value值
public String hget(String key, String fieldKey) {
String value = "";
if (key != null && fieldKey != null) {
JedisPool jedisPool = null;
Jedis jedis = null;
try {
jedisPool = getJedisPool();
if (jedisPool != null) {
jedis = jedisPool.getResource();
String tmp = jedis.hget(key, fieldKey);
value = tmp != null ? tmp : value;
logger.info("jedisTemplate>>>hget key={},fieldKey={},value={} succeed", new Object[] { key, fieldKey, value });
}
} catch (Exception e) {
if (jedisPool != null) {
jedisPool.returnBrokenResource(jedis);
}
logger.error("jedisTemplate>>>hget key={},fieldKey={},value={} failed e={}", new Object[] { key, fieldKey, value, e.getCause() });
} finally {
if (jedisPool != null) {
jedisPool.returnResource(jedis);
}
}
}
return value;
}

public JedisPool getJedisPool() {
return jedisPool;
}

public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}

}


接下来在service中使用
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private JedisTemplate jedisTemplate;

public User getUserByName(String name) {
User u = (User) SerializeUtil.deserialization(jedisTemplate.get("user"));

User user = null;
if (null == u) {

user = userRepository.getUserByUserName(name);
jedisTemplate.set("user", SerializeUtil.serialization(user), 1 * 60 * 60);
} else {
user = u;
}
return user;
}
}

SerializeUtil 是一个序列化的工具类:
public class SerializeUtil {
public static String serialization(Object obj) {
String result = StringUtils.EMPTY;
ObjectOutputStream oos = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
result = bos.toString("ISO-8859-1");
result = URLEncoder.encode(result, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (oos != null) {
oos.close();
oos = null;
}
} catch (Exception e) {
}
return result;
}

}

public static Object deserialization(String serial) {
if (StringUtils.isBlank(serial)) {
return null;
}
ObjectInputStream ois = null;
Object result = null;
try {
String str = URLDecoder.decode(serial, "UTF-8");
ByteArrayInputStream bis = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
ois = new ObjectInputStream(bis);
result = ois.readObject();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (ois != null) {
ois.close();
ois = null;
}
} catch (Exception e) {
}
return result;
}
}
}

再加上controller 调用service方法。 打开本地的redis服务。



















猜你喜欢

转载自aybaylyn.iteye.com/blog/2204099