一般的项目都会用到缓存,因为这样可以提高应用程序的查询速度,无需重新查询数据库或者其它存储介质的数据。jedis针对java开发使用的,那么接下来,笔者就简单介绍下如何在java中使用jedis。
搭建redis服务器
搭建redis服务器当然使用linux系统最好啦,由于笔者没有装linux环境,这里就在本机windows系统上搭建redis服务器。
当然,首先得下载针对windows 32位系统下的redis服务器,下载地址为:https://codeload.github.com/MSOpenTech/redis/zip/2.4.6_win32。
然后,双击redis-server.exe便可启动redis服务器,默认会加载redis.conf文件,相关的配置大家可以去查阅下资料。redis服务器的使用的默认端口是6379,它将会使用键值对的方式存储数据。
在java中使用jedis来缓存数据
首先,创建一个JedisPoolFactory类,用来获取JedisPool实例,代码如下:
package com.qiyongkang.jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisPoolFactory {
private static JedisPool pool = null;
private static JedisPoolConfig config = null;
public static JedisPool getInstance() {
if (pool == null) {
config = new JedisPoolConfig();
config.setMaxActive(1024);
config.setMaxIdle(200);
config.setMaxWait(1000);
config.setTestOnBorrow(true);
config.setTestOnReturn(true);
pool = new JedisPool(config, "127.0.0.1", 6379, 30000);
}
return pool;
}
public static JedisPool getPool() {
return pool;
}
public static void setPool(JedisPool pool) {
JedisPoolFactory.pool = pool;
}
}
然后,再来看看在代码中如何具体使用,如下:
/**
* Project Name:testJava
* File Name:Test.java
* Package Name:com.qiyongkang.jedis
* Date:2015年8月26日上午10:14:03
* Copyright (c) 2015, CANNIKIN(http://http://code.taobao.org/p/cannikin/src/) All Rights Reserved.
*
*/
package com.qiyongkang.jedis;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
public class Test {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// 对象
User user = new User();
user.setId(1);
user.setUserName("qiyongkang");
user.setAge(11);
// user.setAddress(new Address("1", "2"));
loadObjectToRedis("user", String.valueOf(user.getId()), user);
User u = (User) getObjectFromRedis("user", String.valueOf(user.getId()), User.class);
System.out.println("user:" + u);
// map
Map<String, String> map = new HashMap<String, String>();
map.put("id", "2");
map.put("userName", "qiyongkang2");
map.put("age", "22");
map.put("sex", "male");
loadObjectToRedis("map", map.get("id").toString(), map);
Map<String, String> newMap = (Map<String, String>) getObjectFromRedis("map", map.get("id").toString(),
Map.class);
System.out.println("map:" + newMap);
// 对象集合
List<User> useList = new ArrayList<User>();
for (int i = 0; i < 10; i++) {
User o = new User();
o.setId(i);
o.setUserName("qiyongkang" + i);
o.setAge(i);
useList.add(o);
}
loadListToRedis("userList", "id", useList);
User newUser = (User) getObjectFromRedis("userList", "7", User.class);
System.out.println(newUser);
}
/**
*
* loadObjectToRedis:(将一个对象或map放入redis缓存). <br/>
*
* @author QYK
* @param key
* @param fieldKey
* @param obj
* @since JDK 1.6
*/
public static <T> void loadObjectToRedis(String key, String fieldKey, T obj) {
JedisPool jedisPool = null;
Jedis jedis = null;
try {
jedisPool = JedisPoolFactory.getInstance();
jedis = jedisPool.getResource();
JSONObject jsonObject = JSONObject.fromObject(obj);
jedis.hset(key, fieldKey, jsonObject.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/**
*
* loadObjectToRedis:(将一个对象或map放入redis缓存). <br/>
*
* @author QYK
* @param key
* @param fieldKey
* @param obj
* @since JDK 1.6
*/
public static <T> void loadListToRedis(String key, String fieldKeyName, List<T> list) {
JedisPool jedisPool = null;
Jedis jedis = null;
try {
jedisPool = JedisPoolFactory.getInstance();
jedis = jedisPool.getResource();
for (T t : list) {
JSONObject jsonObject = JSONObject.fromObject(t);
//通过反射获取字段的值
Field field = getField(t.getClass(), fieldKeyName);
jedis.hset(key, field.get(t).toString(), jsonObject.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
/**
*
* getObjectFromRedis:(从redis中取出一个对象或map). <br/>
*
* @author QYK
* @param key
* @param fieldKey
* @param clz
* @return
* @since JDK 1.6
*/
@SuppressWarnings("rawtypes")
public static Object getObjectFromRedis(String key, String fieldKey, Class clz) {
Object obj = null;
JedisPool jedisPool = null;
Jedis jedis = null;
try {
jedisPool = JedisPoolFactory.getInstance();
jedis = jedisPool.getResource();
String str = jedis.hget(key, fieldKey);
JSONObject jsonObject = JSONObject.fromObject(str);
obj = JSONObject.toBean(jsonObject, clz);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
return obj;
}
/**
* 通过反射获取某个类的属性
*
* @param clazz
* @param name
* @return
* @throws Exception
*/
private static Field getField(Class<?> clazz, String name) throws Exception {
Field field = null;
for (Field f : clazz.getDeclaredFields()) {
if (f.getName().equals(name)) {
f.setAccessible(true);
field = f;
}
}
return field;
}
}
这里jedis的使用就简单的讲到这儿啦,由于想睡觉啦,有啥问题的可以给我留言,谢谢啦!