1.步骤1 :在配置文件中配置redis 的相关信息 :
## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=redis地址
## Redis服务器连接端口
spring.redis.port=6379
## Redis服务器连接密码(默认为空)
spring.redis.password=密码
## 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
## 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
## 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
## 连接超时时间(毫秒)
spring.redis.timeout=3000
步骤2 : 在子项目的xx-cache中 写redis配置类 :
package com.finance.cmp.dac.cache.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
/**
* 缓存配置声明
*
* @author xiongyu
*/
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.database}")
private int database;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.pool.max-wait}")
private long maxWait;
@Bean
public JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setPassword(password);
factory.setDatabase(database);
factory.setTimeout(timeout);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(maxActive);
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMinIdle(minIdle);
jedisPoolConfig.setMaxWaitMillis(maxWait);
factory.setPoolConfig(jedisPoolConfig);
return factory;
}
@Bean
public RedisTemplate redisTemplate(JedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(jedisConnectionFactory());
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new RedisObjectSerializer());
return template;
}
}
package com.finance.rst.map.engine.backend.cache.config;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
/**
* 缓存对象数据声明
*
* @author xiongyu
*/
public class RedisObjectSerializer implements RedisSerializer
步骤3 : 在子项目service层 的common : 常用方法
package com.finance.cmp.dac.service.common;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.finance.cmp.dac.service.util.SerializeUtil;
@Service
public class RedisCacheService {
@Autowired
RedisTemplate stringRedisTemplate;
/* ----------- common --------- */
public Collection keys(String pattern) {
return stringRedisTemplate.keys(pattern);
}
public void delete(String key) {
stringRedisTemplate.delete(key);
}
public void delete(Collection key) {
stringRedisTemplate.delete(key);
}
public boolean hasKey(String key) {
return stringRedisTemplate.hasKey(key);
}
/**
* get
* @param key
* @return
*/
public Object get(String key) {
Object value = stringRedisTemplate.opsForValue().get(key);
if(value!=null) {
byte[] val=(byte[]) value;
value=SerializeUtil.unserialize(val);
}
return value;
}
/**
*
* @param key
* @param obj
*/
public void set(String key, Object obj) {
if (obj == null) {
return;
}
stringRedisTemplate.opsForValue().set(key, SerializeUtil.serialize(obj));
}
/**
* getString
* @param key
* @return
*/
public String getString(String key){
Object value = stringRedisTemplate.opsForValue().get( key);
String valueRetun = "";
if(value!=null) {
byte[] val=(byte[]) value;
valueRetun=SerializeUtil.unserialize(val).toString();
}
return valueRetun;
}
/**
* getString
* @param key
* @return
*/
public String getStringNoPrefix(String key){
Object value = stringRedisTemplate.opsForValue().get(key);
String valueRetun = "";
if(value!=null) {
byte[] val=(byte[]) value;
valueRetun=SerializeUtil.unserialize(val).toString();
}
return valueRetun;
}
/**
* set key time
* @param key 键
* @param obj 值
* @param timeout 超时时间
* @param unit 超时时间单位 参照TimeUnit
*/
public void setKeyByTime(String key, Object obj, Long timeout, TimeUnit unit) {
if (obj == null) {
return;
}
if (timeout != null) {
stringRedisTemplate.opsForValue().set( key, SerializeUtil.serialize(obj), timeout, unit);
} else {
stringRedisTemplate.opsForValue().set(key, SerializeUtil.serialize(obj));
}
}
}
序列化/反序列化类 :
package com.finance.cmp.ruleEngine.service.util;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializeUtil {
public static byte[] serialize(Object object) {
if (object == null) {
return null;
}
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
try {
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(object);
byte[] bytes = bos.toByteArray();
// set(key.getBytes(), str);
return bytes;
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭输出流
closeOS(oos, bos);
}
return null;
}
public static Object unserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
Object obj = null;
try {
bis = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(new BufferedInputStream(bis));
obj = ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭输入流
closeIS(ois, bis);
}
return obj;
}
/*
*关闭输出流
*/
private static void closeOS(ObjectOutputStream oos, ByteArrayOutputStream bos) {
try {
oos.close();
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/*
*关闭输入流
*/
private static void closeIS(ObjectInputStream ois, ByteArrayInputStream bis) {
try {
ois.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意: 存入redis的类必须实现序列化接口
步骤4 : 使用 在需要的类中引入即可 RedisCacheService
@Autowired
private RedisCacheService redisCacheService;