1.创建工程
创建一个maven项目mavenRedis,pom.xml中添加redis配置:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
如果是一个spring的web工程,还需要添加:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.4.RELEASE</version>
</dependency>
2.基本操作
package mavenRedis;
import org.junit.Test;
import redis.clients.jedis.Jedis;
public class TestRedis {
@Test
public void testRedis(){
//创建一个Redis 客户端
Jedis jedis = new Jedis("192.168.75.105", 6380);
jedis.auth("123456");
//插入数据
// 第三个参数不写为强行产生此key和value,为XX表示key存在才修改、为NX表示不存在时才插入
jedis.set("key1", "HelloWorld");
// 保存5秒
jedis.expire("key1", 5);
String value = jedis.get("key1");
System.out.println(value);
//关闭
jedis.disconnect();}
}
其他操作和命令雷同。
3.线程池
package mavenRedis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtils {
private static JedisPool jedisPool = null;
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
// 最大连接数,低版本使用的是setMaxActive,默认为8,-1为不限制
config.setMaxTotal(1024);
// 允许的最大空闲连接数,默认为8
config.setMaxIdle(200);
// 等待连接的最大时间,低版本使用的是setMaxWait,单位毫秒,默认-1表示永不超时
config.setMaxWaitMillis(10000);
// true表示获取到的jedis实例提前进行了validate操作,确保获取到的实例是可用的
config.setTestWhileIdle(true);
// 表示从连接池中获取连接前是否运行validationQuery,true=运行[默认],false=不运行
config.setTestOnBorrow(true);
// 表示将连接归还连接池前是否运行validationQuery,true=运行,false=不运行[默认];
config.setTestOnReturn(false);
// 连接保持空闲而不被驱逐的最长时间5分钟
config.setMinEvictableIdleTimeMillis(300000);
// 在每次空闲连接回收器线程(如果有)运行时检查的连接数量
config.setNumTestsPerEvictionRun(3);
// 每60秒运行一次空闲连接回收器
config.setTimeBetweenEvictionRunsMillis(60000);
String ip = "192.168.75.105";
int port = 6380;
// 读取超时时间
int readTimeOut = 3000;
// 密码
String auth = "123456";
// 数据库,默认为0
int database = 2;
jedisPool = new JedisPool(config, ip, port, readTimeOut, auth, database);
} catch (Exception e){
e.printStackTrace();
}
}
public synchronized static Jedis getJedis(){
try {
if (jedisPool != null){
return jedisPool.getResource();
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
public static void returnResource(final Jedis jedis){
if (jedis != null){
jedisPool.returnResource(jedis);
}
}
}
使用:
public class TestRedis {
@Test
public void testRedisPool(){
Jedis jedis = RedisUtils.getJedis();
jedis.set("key2", "HelloWorld2");
String value = jedis.get("key2");
RedisUtils.returnResource(jedis);
System.out.println(value);
}
}
将参数放到配置文件中,有三种方法,详见《javaSe》相关章节,方法一直接读文件,但使用不简洁,方法二依赖spring及使用的类需要用注解扫描,方法三依赖spring。为了实用性强,本例使用方法三。
配置文件redis.properties内容:
redis.host=192.168.75.105
redis.port=6380
redis.password=123456
redis.database=2
redis.timeout=5000
redis.userPool=false
redis.pool.maxIdle=200
redis.pool.minIdle=0
redis.pool.maxTotal=1024
redis.pool.maxWaitMillis=3000
redis.pool.minEvictableIdleTimeMillis=300000
redis.pool.numTestsPerEvictionRun=3
redis.pool.timeBetweenEvictionRunsMillis=60000
redis.pool.testOnBorrow=true
redis.pool.testOnReturn=true
redis.pool.testWhileIdle=true
Spring中添加配置:
<bean class="com.harvetech.utils.PropertyConfigurerUtils">
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
PropertyConfigurerUtils 类如下:
package com.harvetech.utils;
import java.util.HashMap;
public class PropertyConfigurerUtils extends PropertyPlaceholderConfigurer {
private static Map<String, String> propertiesMap = new HashMap<String, String>();
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
System.out.println(key+" : " +value);
propertiesMap.put(keyStr, value);
}
}
public static String getProperty(String name) {
return propertiesMap.get(name);
}
}
RedisUtils类改造:
package mavenRedis;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtils {
private static JedisPool jedisPool = null;
// 读取超时时间
static int readTimeOut = Integer.valueOf(PropertyConfigurerUtils.getProperty("redis.timeout"));
static String ip = PropertyConfigurerUtils.getProperty("redis.host");
static int port = Integer.valueOf(PropertyConfigurerUtils.getProperty("redis.port"));
static String auth = PropertyConfigurerUtils.getProperty("redis.password");
static int database = Integer.valueOf(PropertyConfigurerUtils.getProperty("redis.database"));
static int maxTotal = Integer.valueOf(PropertyConfigurerUtils.getProperty("redis.pool.maxTotal"));
static int maxIdle = Integer.valueOf(PropertyConfigurerUtils.getProperty("redis.pool.maxIdle"));
static int minIdle = Integer.valueOf(PropertyConfigurerUtils.getProperty("redis.pool.minIdle"));
static long maxWaitMillis = Long.valueOf(PropertyConfigurerUtils.getProperty("redis.pool.maxWaitMillis"));
static boolean testOnBorrow = "true".equals(PropertyConfigurerUtils.getProperty("redis.pool.testOnBorrow"));
static boolean testOnReturn = "true".equals(PropertyConfigurerUtils.getProperty("redis.pool.testOnReturn"));
static boolean testWhileIdle = "true".equals(PropertyConfigurerUtils.getProperty("redis.pool.testWhileIdle"));
static long minEvictableIdleTimeMillis = Long.valueOf(PropertyConfigurerUtils.getProperty("redis.pool.minEvictableIdleTimeMillis"));
static int numTestsPerEvictionRun = Integer.valueOf(PropertyConfigurerUtils.getProperty("redis.pool.numTestsPerEvictionRun"));
static long timeBetweenEvictionRunsMillis = Long.valueOf(PropertyConfigurerUtils.getProperty("redis.pool.timeBetweenEvictionRunsMillis"));
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
// 最大连接数,低版本使用的是setMaxActive,默认为8,-1为不限制
config.setMaxTotal(maxTotal);
// 允许的最大空闲连接数,默认为8
config.setMaxIdle(maxIdle);
// 允许的最小空闲连接数
config.setMinIdle(minIdle);
// 等待连接的最大时间,低版本使用的是setMaxWait,单位毫秒,默认-1表示永不超时
config.setMaxWaitMillis(maxWaitMillis);
// true表示获取到的jedis实例提前进行了validate操作,确保获取到的实例是可用的
config.setTestWhileIdle(testWhileIdle);
// 表示从连接池中获取连接前是否运行validationQuery,true=运行[默认],false=不运行
config.setTestOnBorrow(testOnBorrow);
// 表示将连接归还连接池前是否运行validationQuery,true=运行,false=不运行[默认];
config.setTestOnReturn(testOnReturn);
// 连接保持空闲而不被驱逐的最长时间5分钟
config.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
// 在每次空闲连接回收器线程(如果有)运行时检查的连接数量
config.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
// 每60秒运行一次空闲连接回收器
config.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
jedisPool = new JedisPool(config, ip, port, readTimeOut, auth, database);
} catch (Exception e){
e.printStackTrace();
}
}
public synchronized static Jedis getJedis(){
try {
if (jedisPool != null){
return jedisPool.getResource();
}
} catch (Exception e){
e.printStackTrace();
}
return null;
}
public static void returnResource(final Jedis jedis){
if (jedis != null){
jedisPool.returnResource(jedis);
}
}
}
使用redis的地方:
private Jedis jedis = RedisUtils.getJedis();
jedis.set("key2", "44");
4.集成spring
配置文件和上面一样,spring中添加配置项:
<bean id="propConf" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="nullValue" value="@null" />
<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
<property name="ignoreResourceNotFound" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="fileEncoding" value="UTF-8" />
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
<import resource="classpath:redis.xml"/>
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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd"
default-lazy-init="true">
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="minIdle" value="${redis.pool.minIdle}" />
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<property name="maxWaitMillis" value="${redis.pool.maxWaitMillis}" />
<property name="minEvictableIdleTimeMillis" value="${redis.pool.minEvictableIdleTimeMillis}"></property>
<property name="numTestsPerEvictionRun" value="${redis.pool.numTestsPerEvictionRun}"></property>
<property name="timeBetweenEvictionRunsMillis" value="${redis.pool.timeBetweenEvictionRunsMillis}"></property>
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
<property name="testOnReturn" value="${redis.pool.testOnReturn}" />
<property name="testWhileIdle" value="${redis.pool.testWhileIdle}"></property>
</bean>
<bean id="jedisConnectionFactory"
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.password}" />
<property name="database" value="${redis.database}" />
<property name="poolConfig" ref="jedisPoolConfig" />
</bean>
<bean class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="jedisConnectionFactory" />
</beans>
定义redis工具类RedisTool:
package com.harvetech.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/**
* 功能:redis工具类
* 创建时间:2017年9月6日
*/
@Component
public class RedisTool {
@Autowired
private RedisTemplate redisTemplate;
private Integer database;
public Integer getDatabase() {
return database;
}
public void setDatabase(Integer database) {
this.database = database;
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void set(final String key, final String value) {
redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
if (database != null){
connection.select(database);
}
connection.set(key.getBytes(), value.getBytes());
return 1L;
}
});
}
/**
* @param liveTime 存活时间/秒
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public void set(final String key, final String value, final long liveTime) {
redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
if (database != null){
connection.select(database);
}
connection.setEx(key.getBytes(), liveTime, value.getBytes());
return 1L;
}
});
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void set(final String key, final Integer value) {
redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
if (database != null){
connection.select(database);
}
connection.set(key.getBytes(), intToBytes(value));
return 1L;
}
});
}
@SuppressWarnings({"unchecked", "rawtypes"})
public String get(final String key) {
return (String) redisTemplate.execute(new RedisCallback() {
public Object doInRedis(RedisConnection connection) throws DataAccessException {
try {
if (database != null){
connection.select(database);
}
return new String(connection.get(key.getBytes()));
} catch (Exception e) {
}
return null;
}
});
}
/**
* 描述: 自增 key不存在则为1
*/
@SuppressWarnings({"unchecked", "rawtypes"})
public Long incrby(final String key) {
return (Long)redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
if (database != null){
connection.select(database);
}
Long incr = connection.incr(key.getBytes());
return incr;
}
});
}
@SuppressWarnings({"unchecked", "rawtypes"})
public Long decrby(final String key) {
return (Long)redisTemplate.execute(new RedisCallback() {
public Long doInRedis(RedisConnection connection) throws DataAccessException {
if (database != null){
connection.select(database);
}
Long incr = connection.decr(key.getBytes());
return incr;
}
});
}
@SuppressWarnings({"unchecked", "rawtypes"})
public Long del(final String key){
return (Long)redisTemplate.execute(new RedisCallback<Object>(){
public Long doInRedis(RedisConnection connection) throws DataAccessException {
if (database != null){
connection.select(database);
}
return connection.del(key.getBytes());
}
});
}
public static byte[] intToBytes( int value )
{
byte[] src = new byte[4];
src[3] = (byte) ((value>>24) & 0xFF);
src[2] = (byte) ((value>>16) & 0xFF);
src[1] = (byte) ((value>>8) & 0xFF);
src[0] = (byte) (value & 0xFF);
return src;
}
}
使用的地方:
@Resource
private RedisTool redisTool;
redisTool.set("key1","23");