您的位置:首页 > 数据库 > Redis

1 redis在spring中的配置及java代码实现 2 redis在java项目中的使用

2017-10-20 17:29 836 查看


redis在spring中的配置及java代码实现

1、建一个redis.properties属性文件

# Redis Setting
redis.addr = 127.0.0.1
redis.port = 6379
redis.auth = master

redis.maxIdle = 200
redis.maxActive = 1024
redis.maxWait = 10000
redis.timeOut = 10000
redis.testOnBorrow = true


2、新建一个RedisUtil.java文件,文件代码如下:


package cn.com.taiji.sample.utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class RedisUtil implements Serializable{

private static final long serialVersionUID = -1149678082569464779L;

//Redis服务器IP
private static String addr;

//Redis的端口号
private static int port;

//访问密码
private static String auth;

//可用连接实例的最大数目,默认值为8;
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int maxActive;

//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int maxIdle;

//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int maxWait;

private static int timeOut;

//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean testOnBorrow;

public static Jedis jedis;//非切片额客户端连接

public static JedisPool jedisPool;//非切片连接池

public static ShardedJedis shardedJedis;//切片额客户端连接

public static ShardedJedisPool shardedJedisPool;//切片连接池

/**
* 初始化非切片池
*/
private static void initialPool()
{
// 池基本配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxActive);
config.setMaxIdle(maxIdle);
config.setMaxWaitMillis(maxWait);
config.setTestOnBorrow(testOnBorrow);
jedisPool = new JedisPool(config, addr, port);
}

/**
* 初始化切片池
*/
private static  void initialShardedPool()
{
// 池基本配置
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxActive);
config.setMaxIdle(maxIdle);
config.setMaxWaitMillis(maxWait);
config.setTestOnBorrow(testOnBorrow);
// slave链接
List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
shards.add(new JedisShardInfo(addr, port, auth));

// 构造池
shardedJedisPool = new ShardedJedisPool(config, shards);
}

public  static void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
initialPool();
initialShardedPool();
try {
shardedJedis = shardedJedisPool.getResource();
} catch (Exception e) {
System.out.println("连接shardedJedisPool失败!");
}
try {
jedis = jedisPool.getResource();
} catch (Exception e) {
System.out.println("连接jedisPool失败!");
}
}

public String getAddr() {
return addr;
}

public void setAddr(String addr) {
this.addr = addr;
}

public int getPort() {
return port;
}

public void setPort(int port) {
this.port = port;
}

public String getAuth() {
return auth;
}

public void setAuth(String auth) {
this.auth = auth;
}

public int getMaxActive() {
return maxActive;
}

public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}

public int getMaxIdle() {
return maxIdle;
}

public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}

public int getMaxWait() {
return maxWait;
}

public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}

public int getTimeOut() {
return timeOut;
}

public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}

public boolean isTestOnBorrow() {
return testOnBorrow;
}

public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
}


在set方法中会飘黄,不影响使用。

3、在spring-servlet.xml配置文件中,加入以下代码:

<context:component-scan base-package="cn.com.taiji.sample.config.web" />
<context:property-placeholder location="file:#{systemProperties['webapp.sample']}/WEB-INF/conf/redis.properties" />

<bean id="redisUtil" class="cn.com.taiji.sample.utils.RedisUtil">
<property name="addr"><value>${redis.addr}</value></property>
<property name="port"><value>${redis.port}</value></property>
<property name="auth"><value>${redis.auth}</value></property>
<property name="maxIdle"><value>${redis.maxIdle}</value></property>
<property name="maxActive"><value>${redis.maxActive}</value></property>
<property name="maxWait"><value>${redis.maxWait}</value></property>
<property name="timeOut"><value>${redis.timeOut}</value></property>
<property name="testOnBorrow"><value>${redis.testOnBorrow}</value></property>
</bean>


<context:property-placeholder location="" />指的是redis.properties的文件路径。
到此,redis的spring配置就已经完成了。
下一篇将介绍redis在java项目中的使用。

   

2 redis在java项目中的使用

在上一篇文章中已经讲了redis的spring配置,这篇将会描述redis在java项目中的使用。

redis存储形式都是key-value(键值对),按照存储的内容分为两种,一种是存简单数据,即数字,字符串等,可以用string-value的形式存储;另一种是存对象、集合等,最好用序列化的方式来存储。

1、存储简单数据

try {
Jedis jedis = new Jedis();
jedis.set("name", "JackGSmith");
} catch (Exception e) {
//如果缓存连不上,则不处理
System.out.println("登录无法更新该用户缓存");
}


从redis缓存中获取key为“name”的值,使用jedis.get("name"),用一个String变量接收即可。

2、存储对象、集合

存对象集合用序列化的方式存储,用反序列化的方式取值。存储的key和value都是转化成字节码的形式。

先定义一个抽象类:SerializeTranscoder.java,代码如下:

package cn.com.taiji.sample.utils;

import java.io.Closeable;
import java.io.IOException;

public abstract class SerializeTranscoder {

public abstract byte[] serialize(Object value);

public abstract Object deserialize(byte[] in) throws IOException;

public void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}


再建一个序列化的类,ObjectTranscoder.java,继承上面这个抽象类,该类是用来序列化存储对象用的,代码如下:

package cn.com.taiji.sample.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectTranscoder<M extends Serializable> extends SerializeTranscoder{

@SuppressWarnings("unchecked")
@Override
public byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] result = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
M m = (M) value;
os.writeObject(m);
os.close();
bos.close();
result = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
}
return result;
}

@SuppressWarnings("unchecked")
@Override
public M deserialize(byte[] in) {
M result = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
result = (M) is.readObject();
is.close();
bis.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
close(is);
close(bis);
}
return result;
}
}


接着在新建一个ListTranscoder.java文件,用来序列化存储List(集合)对象,基本同上,代码如下:

package cn.com.taiji.sample.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class ListTranscoder<M extends Serializable> extends SerializeTranscoder {

@SuppressWarnings("unchecked")
public List<M> deserialize(byte[] in) throws IOException {
List<M> list = new ArrayList<>();
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
while (true) {
M m = (M)is.readObject();
if (m == null) {
break;
}
list.add(m);
}
is.close();
bis.close();
}
} catch (Exception e) {
//  e.printStackTrace();
}  finally {
is.close();
bis.close();
}
return  list;
}

@SuppressWarnings("unchecked")
@Override
public byte[] serialize(Object value) {
if (value == null)
throw new NullPointerException("Can't serialize null");

List<M> values = (List<M>) value;
byte[] results = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;

try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
for (M m : values) {
os.writeObject(m);
}
results = bos.toByteArray();
os.close();
bos.close();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
}
return results;
}
}


现在,就可以用序列化的方式存储对象或集合了:

try {
Jedis jedis = new Jedis();
List<SystemNotice> noticeList = systemNoticeManager.listQuery(noticeQModel);
if(noticeList.size()>0 && noticeList != null){
ListTranscoder<SystemNotice> listTranscoder = new ListTranscoder<SystemNotice>();
jedis.set(loginUser.getId().getBytes(), listTranscoder.serialize(noticeList));
}
} catch (Exception e) {
//如果缓存连不上,则不处理
System.out.println("登录无法更新该用户缓存");
}


存的key使用用户id,所以取出list就很简单了:

try {
Jedis jedis = new Jedis();
byte[] list = jedis.get(loginUser.getId().getBytes());
ListTranscoder<SystemNotice> listTranscoder = new ListTranscoder<SystemNotice>();
List<SystemNotice> newList = listTranscoder.deserialize(list);try {
  responseJson(JsonTools.toJsonStr(newList), response);
} catch (IOException e) {
e.printStackTrace();
}
}


至此,redis在java项目中的使用就到此结束了。关于redis的其他命令,可以自己去百度下。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: