沃梦达 / 编程技术 / 数据库 / 正文

通用redis

import lombok.extern.slf4j.Slf4j;import org.apache.poi.ss.formula.functions.T;import org.rcisoft.core.converter.ListTranscoder;import org.rcisoft.core.service.RcRedisService;import org.springframework...



import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.rcisoft.core.converter.ListTranscoder;
import org.rcisoft.core.service.RcRedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

@Service
@Slf4j
public class RcRedisServiceImpl implements RcRedisService {

@Autowired
private JedisPool jedisPool;

ListTranscoder listTranscoder;
@Override
public Jedis getResource() {
return jedisPool.getResource();
}

@SuppressWarnings("deprecation")
@Override
public void returnResource(Jedis jedis) {
if(jedis != null){
jedisPool.returnResourceObject(jedis);
}
}

@Override
public void set(String key, String value,int expire) {
Jedis jedis=null;
try{
jedis = getResource();
jedis.set(key, value);
if (expire > 0)
jedis.expire(key,expire);
log.info("Redis set success - " + key + ", value:" + value);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
}finally{
returnResource(jedis);
}
}

@Override
public void setListObj(String key, byte[] value) {
Jedis jedis=null;
try{
jedis = getResource();
jedis.set(key.getBytes(), value);
log.info("Redis set success - " + key + ", value:" + value);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
}finally{
returnResource(jedis);
}
}

@Override
public <T> void setListObj(String key, List<T> value, int expire) {
Jedis jedis=null;
try{
jedis = getResource();
jedis.set(key.getBytes(), listTranscoder.serialize(value));
if (expire > 0)
jedis.expire(key.getBytes(),expire);
log.info("Redis set success - " + key + ", value:" + value);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
}finally{
returnResource(jedis);
}
}

@Override
public void set(String key, String value) {
Jedis jedis=null;
try{
jedis = getResource();
jedis.set(key, value);
log.info("Redis set success - " + key + ", value:" + value);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
}finally{
returnResource(jedis);
}
}

@Override
public void setBytes(String key, byte[] value) {
Jedis jedis=null;
try{
jedis = getResource();
jedis.set(key.getBytes(), value);
log.info("Redis set success - " + key + ", value:" + value);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
}finally{
returnResource(jedis);
}
}

@Override
public void setBytes(String key, byte[] value,int expire) {
Jedis jedis=null;
try{
jedis = getResource();
jedis.set(key.getBytes(), value);
if (expire > 0)
jedis.expire(key,expire);
log.info("Redis set success - " + key + ", value:" + value);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
}finally{
returnResource(jedis);
}
}
@Override
public String get(String key) {
String result = null;
Jedis jedis=null;
try{
jedis = getResource();
result = jedis.get(key);
log.info("Redis get success - " + key + ", value:" + result);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + result);
}finally{
returnResource(jedis);
}
return result;
}

@Override
public byte[] getBytes(String key) {
byte[] result = null;
Jedis jedis=null;
try{
jedis = getResource();
result = jedis.get(key.getBytes());
log.info("Redis get success - " + key + ", value:" + result);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + result);
}finally{
returnResource(jedis);
}
return result;
}

@Override
public void remove(String key) {
Jedis jedis=null;
try{
jedis = getResource();
jedis.del(key);
log.info("Redis del success - " + key );
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key );
}finally{
returnResource(jedis);
}

}

@Override
public List getList(String key) {
Jedis jedis=null;
List result = null ;
try{
jedis = getResource();
result = jedis.lrange(key, 0, -1);
log.info("Redis get list success - " + key + ", value:" + result);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key );
}finally{
returnResource(jedis);
}
return result;
}

@Override
public List getListObj(String key) {
Jedis jedis=null;
List result = null ;
try{
jedis = getResource();
byte[] in = jedis.get(key.getBytes());
result = listTranscoder.deserialize(in);
// result = jedis.lrange(key, 0, -1);
log.info("Redis get list success - " + key + ", value:" + result);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key );
}finally{
returnResource(jedis);
}
return result;
}



@Override
public void setList(String key, String value) {
Jedis jedis=null;
try{
jedis = getResource();
jedis.rpush(key, value);
log.info("Redis set list success - " + key + ", value:" + value);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
}finally{
returnResource(jedis);
}
}

@Override
public void removeList(String key,String value) {
Jedis jedis=null;
try{
jedis = getResource();
jedis.lrem(key,1,value);
log.info("Redis remove list success - " + key + ", value:" + value);
} catch (Exception e) {
e.printStackTrace();
log.error("Redis set error: "+ e.getMessage() +" - " + key + ", value:" + value);
}finally{
returnResource(jedis);
}
}
}



JedisPool.java

package redis.clients.jedis;

import java.net.URI;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocketFactory;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import redis.clients.jedis.exceptions.JedisException;
import redis.clients.util.JedisURIHelper;
import redis.clients.util.Pool;

public class JedisPool extends Pool<Jedis> {

public JedisPool() {
this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) {
this(poolConfig, host, Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
}

public JedisPool(String host, int port) {
this(new GenericObjectPoolConfig(), host, port, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null);
}

public JedisPool(final String host) {
URI uri = URI.create(host);
if (JedisURIHelper.isValid(uri)) {
String h = uri.getHost();
int port = uri.getPort();
String password = JedisURIHelper.getPassword(uri);
int database = JedisURIHelper.getDBIndex(uri);
boolean ssl = uri.getScheme().equals("rediss");
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(h, port,
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, password, database, null,
ssl, null, null, null), new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(host,
Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null, false, null, null, null), new GenericObjectPoolConfig());
}
}

public JedisPool(final String host, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
URI uri = URI.create(host);
if (JedisURIHelper.isValid(uri)) {
String h = uri.getHost();
int port = uri.getPort();
String password = JedisURIHelper.getPassword(uri);
int database = JedisURIHelper.getDBIndex(uri);
boolean ssl = uri.getScheme().equals("rediss");
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(h, port,
Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, password, database, null, ssl,
sslSocketFactory, sslParameters, hostnameVerifier),
new GenericObjectPoolConfig());
} else {
this.internalPool = new GenericObjectPool<Jedis>(new JedisFactory(host,
Protocol.DEFAULT_PORT, Protocol.DEFAULT_TIMEOUT, Protocol.DEFAULT_TIMEOUT, null,
Protocol.DEFAULT_DATABASE, null, false, null, null, null), new GenericObjectPoolConfig());
}
}

public JedisPool(final URI uri) {
this(new GenericObjectPoolConfig(), uri, Protocol.DEFAULT_TIMEOUT);
}

public JedisPool(final URI uri, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(new GenericObjectPoolConfig(), uri, Protocol.DEFAULT_TIMEOUT, sslSocketFactory,
sslParameters, hostnameVerifier);
}

public JedisPool(final URI uri, final int timeout) {
this(new GenericObjectPoolConfig(), uri, timeout);
}

public JedisPool(final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(new GenericObjectPoolConfig(), uri, timeout, sslSocketFactory, sslParameters,
hostnameVerifier);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, null);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final boolean ssl) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, null, ssl);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, null, ssl,
sslSocketFactory, sslParameters, hostnameVerifier);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final boolean ssl) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null,
ssl);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, null, Protocol.DEFAULT_DATABASE, null,
ssl, sslSocketFactory, sslParameters, hostnameVerifier);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final int timeout) {
this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE, null);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final int timeout, final boolean ssl) {
this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE, null, ssl);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, final int port,
final int timeout, final boolean ssl, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, timeout, null, Protocol.DEFAULT_DATABASE, null, ssl,
sslSocketFactory, sslParameters, hostnameVerifier);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database) {
this(poolConfig, host, port, timeout, password, database, null);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final boolean ssl) {
this(poolConfig, host, port, timeout, password, database, null, ssl);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, timeout, password, database, null, ssl, sslSocketFactory,
sslParameters, hostnameVerifier);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final String clientName) {
this(poolConfig, host, port, timeout, timeout, password, database, clientName, false,
null, null, null);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final String clientName,
final boolean ssl) {
this(poolConfig, host, port, timeout, timeout, password, database, clientName, ssl,
null, null, null);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
int timeout, final String password, final int database, final String clientName,
final boolean ssl, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(poolConfig, host, port, timeout, timeout, password, database, clientName, ssl,
sslSocketFactory, sslParameters, hostnameVerifier);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port,
final int connectionTimeout, final int soTimeout, final String password, final int database,
final String clientName, final boolean ssl, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
super(poolConfig, new JedisFactory(host, port, connectionTimeout, soTimeout, password,
database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier));
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri) {
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT, sslSocketFactory, sslParameters,
hostnameVerifier);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout) {
this(poolConfig, uri, timeout, timeout);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(poolConfig, uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier);
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final int connectionTimeout, final int soTimeout) {
super(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, null, false,
null, null, null));
}

public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri,
final int connectionTimeout, final int soTimeout, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
super(poolConfig, new JedisFactory(uri, connectionTimeout, soTimeout, null,
(uri.getScheme() !=null && uri.getScheme().equals("rediss")), sslSocketFactory,
sslParameters, hostnameVerifier));
}

@Override
public Jedis getResource() {
Jedis jedis = super.getResource();
jedis.setDataSource(this);
return jedis;
}

/**
* @deprecated starting from Jedis 3.0 this method will not be exposed. Resource cleanup should be
* done using @see {@link redis.clients.jedis.Jedis#close()}
*/
@Override
@Deprecated
public void returnBrokenResource(final Jedis resource) {
if (resource != null) {
returnBrokenResourceObject(resource);
}
}

/**
* @deprecated starting from Jedis 3.0 this method will not be exposed. Resource cleanup should be
* done using @see {@link redis.clients.jedis.Jedis#close()}
*/
@Override
@Deprecated
public void returnResource(final Jedis resource) {
if (resource != null) {
try {
resource.resetState();
returnResourceObject(resource);
} catch (Exception e) {
returnBrokenResource(resource);
throw new JedisException("Could not return the resource to the pool", e);
}
}
}
}


RedisConfig.java
import lombok.extern.slf4j.Slf4j;
import org.rcisoft.core.bean.RcRedisConfigBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;



@Configuration
@Slf4j
public class RedisConfig {

@Autowired
private RcRedisConfigBean redisConfigBean;

@Bean
public JedisPool getJedisPool(){
JedisPoolConfig config = new JedisPoolConfig();
//连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
config.setBlockWhenExhausted(true);
//设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
//是否启用pool的jmx管理功能, 默认true
config.setJmxEnabled(true);
//MBean ObjectName = new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=" + "pool" + i); 默认为"pool", JMX不熟,具体不知道是干啥的...默认就好.
config.setJmxNamePrefix("pool");
//是否启用后进先出, 默认true
config.setLifo(false);
//最大空闲连接数, 默认8个
config.setMaxIdle(redisConfigBean.getMaxIdle());
//最大连接数, 默认8个
config.setMaxTotal(redisConfigBean.getMaxActive());
//获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1
config.setMaxWaitMillis(redisConfigBean.getMaxWait());
//逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
config.setMinEvictableIdleTimeMillis(1800000);
//最小空闲连接数, 默认0
config.setMinIdle(0);
//每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
config.setNumTestsPerEvictionRun(3);
//对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断 (默认逐出策略)
config.setSoftMinEvictableIdleTimeMillis(1800000);
//在获取连接的时候检查有效性, 默认false
config.setTestOnBorrow(false);
//在空闲时检查有效性, 默认false
config.setTestWhileIdle(false);
//逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
config.setTimeBetweenEvictionRunsMillis(-1);

JedisPool pool = new JedisPool(config,redisConfigBean.getHost(),redisConfigBean.getPort(),
redisConfigBean.getTimeout(),redisConfigBean.getPassword(),redisConfigBean.getDatabase());
log.info("init JedisPool ...");
return pool;
}
}


RcRedisService.java
import redis.clients.jedis.Jedis;

import java.util.List;

public interface RcRedisService {

/**
* 获取jedis
* @return
*/
public Jedis getResource();

/**
* 归还jedis
* @param jedis
*/
public void returnResource(Jedis jedis);

/**
* 赋值
* @param key
* @param value
*/
public void set(String key, String value);
/**
* 赋值字节数组 设置过期
* @param key
* @param value
*/
public void set(String key, String value, int expire);

/**
* 赋值
* @param key
* @param value
*/
public void setListObj(String key, byte[] value);
/**
* 赋值字节数组 设置过期
* @param key
* @param
*/
<T> void setListObj(String key, List<T> value, int expire);


/**
* 赋值字节数组
* @param key
* @param value
*/
public void setBytes(String key, byte[] value);
/**
* 赋值字节数组 设置过期
* @param key
* @param value
*/
public void setBytes(String key, byte[] value, int expire);

/**
* 取值
* @param key
* @return
*/
public String get(String key);

/**
* 取值数组
* @param key
* @return
*/
public byte[] getBytes(String key);

/**
* 清除
* @param key
*/
public void remove(String key);

/**
* 获取list
* @param key
*/
public List getList(String key);

public List getListObj(String key);

/**
* set list
* @param key
* @param value
*/
public void setList(String key, String value);

/**
* 从 list 中 删除
* @param key
*/
public void removeList(String key, String value);
}


RedisConfigBean.java

 

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;


@Component
@ConfigurationProperties(prefix = "spring.redis")
@Data
public class RcRedisConfigBean {

private String host;

private int port;

@Value("${spring.redis.password}")
private String password;

private int timeout;

private int database;


@Value("${spring.redis.pool.max-idle:100}")
private int maxIdle;

@Value("${spring.redis.pool.max-active:100}")
private int maxActive;

@Value("${spring.redis.pool.min-idle:1}")
private int minIdle;

@Value("${spring.redis.pool.max-wait:-1}")
private int maxWait;

 

}

本文标题为:通用redis

基础教程推荐