redis是高性能的key-value数据库和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)现在这里主要是搭建reids缓存。
本环境框架是spring-boot,用的是本地redis
1.确保本地redis已经启动
2.创建一个springboot 项目
一直下一步,创建springboot项目成功
配置mavne依赖
添加pom。xml依赖
org.springframework.boot
spring-boot-starter-web
redis.clients
jedis
2.9.0
3.redis配置
此处要设置redis的密码(不会的百度)
定义配置,初始化spring容器
@Configuration
public class RedisConfig {
@Bean(name = "jedis.pool")
@Autowired
public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config,
@Value("${jedis.pool.host}") String host,
@Value("${jedis.pool.port}") int port, @Value("${jedis.pool.timeout}")int timeout, @Value("${jedis.pool.password}")String password) {
return new JedisPool(config, host, port,timeout,password);
}
@Bean(name = "jedis.pool.config")
public JedisPoolConfig jedisPoolConfig(@Value("${jedis.pool.config.maxTotal}") int maxTotal,
@Value("${jedis.pool.config.maxIdle}") int maxIdle,
@Value("${jedis.pool.config.maxWaitMillis}") int maxWaitMillis) {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMaxWaitMillis(maxWaitMillis);
return config;
}
}
4开始写java缓存代码
1). 创建一个缓存工程
/**
* 缓存 工厂
*/
public class CacheManageFactory {
public static CacheManager getInstance(){
CacheManager cm = getCacheManager("redis");
return cm;
}
public static CacheManager getCacheManager(String name) {
if ("redis".equals(name)) {
return RedisClient.getInstance();
} else {
System.out.println("未指定缓存");
}
return null;
}
}
2). Jedis Cache 工具类
package com.springboot.demo.cache;
import com.springboot.demo.util.ObjectUtils;
import com.springboot.demo.util.SpringContextHolder;
import com.springboot.demo.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;
import java.util.List;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;
/**
* Jedis Cache 工具类
*/
public class RedisClient implements CacheManager {
private static Logger logger = LoggerFactory.getLogger(RedisClient.class);
private static RedisClient redisClient;
private static JedisPool jedisPool = SpringContextHolder.getBean(JedisPool.class);
private static ReentrantLock lock = new ReentrantLock();
public static RedisClient getInstance() {
if (redisClient == null) {
lock.lock();
if (redisClient == null) {
redisClient = new RedisClient();
}
lock.unlock();
}
return redisClient;
}
/**
* 获取资源
*
* @return
* @throws JedisException
*/
public Jedis getResource() throws JedisException {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
} catch (JedisException e) {
logger.warn("getResource.", e);
returnBrokenResource(jedis);
throw e;
}
return jedis;
}
/**
* 归还资源
*
* @param jedis
*/
public void returnBrokenResource(Jedis jedis) {
if (jedis != null) {
jedisPool.returnBrokenResource(jedis);
}
}
/**
* 释放资源
*
* @param jedis
*/
public static void returnResource(Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
/**
* 获取byte[]类型Key
*
* @param object
* @return
*/
public byte[] getBytesKey(Object object) {
if (object instanceof String) {
return StringUtil.getBytes((String) object);
} else {
return ObjectUtils.serialize(object);
}
}
/**
* Object转换byte[]类型
*
* @param object
* @return
*/
public byte[] toBytes(Object object) {
return ObjectUtils.serialize(object);
}
/**
* byte[]型转换Object
*
* @param bytes
* @return
*/
public Object toObject(byte[] bytes) {
if (null == bytes) {
return null;
}
return ObjectUtils.unserialize(bytes);
}
/**
* 永久保存键值
*
* @param key 键
* @param value 值
* @return
*/
@Override
public String set(String key, Object value) {
String result = null;
Jedis jedis = null;
if (StringUtil.isBlank(key)) {
return "0";
}
try {
jedis = getResource();
result = jedis.set(getBytesKey(key), toBytes(value));
} catch (Exception e) {
logger.warn("setObject {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 永久保存键值,并设置缓存时间(秒)
*
* @param key 键
* @param value 值
* @param timeSeconds 缓存时间(秒),0 为不超时
* @return
*/
@Override
public String set(String key, Object value, int timeSeconds) {
String result = null;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.set(getBytesKey(key), toBytes(value));
if (timeSeconds != 0) {
jedis.expire(key, timeSeconds);
}
} catch (Exception e) {
logger.warn("set {} = {}", key, value, timeSeconds, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 根据键获取值
*
* @param key 键
* @return
*/
@Override
public T get(String key) {
if (StringUtil.isBlank(key)) {
return null;
}
T result = null;
Jedis jedis = null;
try {
jedis = getResource();
result = (T) toObject(jedis.get(getBytesKey(key)));
} catch (Exception e) {
logger.warn("getObject {} = {}", key, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 根据键判断缓存是否存在
*
* @param key 键
* @return
*/
@Override
public boolean exists(String key) {
boolean result = false;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.exists(getBytesKey(key));
} catch (Exception e) {
logger.warn("exists {}", key, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 根据键设置缓存生存时间(秒)
*
* @param key 键
* @param timeSecond 生存时间(秒)
* @return
*/
@Override
public long expire(String key, int timeSecond) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
if (timeSecond != 0) {
jedis.expire(key, timeSecond);
}
} catch (Exception e) {
logger.warn("setSet {} = {}", key, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 根据键删除缓存
*
* @param key 键
* @return
*/
@Override
public long deleteByKey(String key) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(getBytesKey(key))) {
result = jedis.del(getBytesKey(key));
}
} catch (Exception e) {
logger.warn("delObject {}", key, e);
} finally {
returnResource(jedis);
}
return result;
}
@Override
public String getStringHash(String key) {
Jedis jedis = null;
String result = null;
try {
jedis = getResource();
result = jedis.hget(key, "redis");
} catch (Exception e) {
logger.warn("getObjectList {} = {}", key, "redis", e);
} finally {
returnResource(jedis);
}
return result;
}
@Override
public Long setStringHash(String key, String value, int timeSeconds) {
Jedis jedis = null;
Long result = null;
try {
jedis = getResource();
result = jedis.hset(key, "redis", value);
if (timeSeconds != 0) {
jedis.expire(key, timeSeconds);
}
} catch (Exception e) {
logger.warn("getObjectList {} = {}", key, "redis", e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 删除缓存
*/
@Override
public Long delHashValue(String key) {
Jedis jedis = null;
Long result = Long.valueOf(0);
try {
jedis = getResource();
result = jedis.hdel(key, "redis");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 设置Set缓存
*
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
@Override
public long setSet(String key, Set value, int cacheSeconds) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
jedis.del(key);
}
result = jedis.sadd(key, (String[]) value.toArray());
if (cacheSeconds != 0) {
jedis.expire(key, cacheSeconds);
}
} catch (Exception e) {
logger.warn("setSet {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取缓存
*
* @param key 键
* @return 值
*/
@Override
public Set getSet(String key) {
Set value = null;
Jedis jedis = null;
try {
jedis = getResource();
if (jedis.exists(key)) {
value = jedis.smembers(key);
}
} catch (Exception e) {
logger.warn("getSet {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return value;
}
/**
* 向Set缓存中添加值
*
* @param key 键
* @param value 值
* @return
*/
@Override
public long setSetAdd(String key, String... value) {
long result = 0;
Jedis jedis = null;
try {
jedis = getResource();
result = jedis.sadd(key, value);
//logger.debug("setSetAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetAdd {} = {}", key, value, e);
} finally {
returnResource(jedis);
}
return result;
}
/**
* 获取List缓存(自定义) json串
*
* @param key 键
* @return 值
*/
@Override
public String getObjectListNew(String key) {
List
3)。缓存接口
package com.springboot.demo.cache;
import java.util.Set;
/**
* 缓存接口
*/
public interface CacheManager {
/**
* 永久保存键值
*
* @param key 键
* @param obj 值
* @return
*/
String set(String key, Object obj);
/**
* 保存键值并指定存储时长,单位秒。
*
* @param key 键
* @param obj 值
* @param timeSecond 缓存时间(秒),0 为不超时
* @return
*/
String set(String key, Object obj, int timeSecond);
/**
* 根据键获取值
*
* @param key 键
* @param 返回存入值
* @return
*/
T get(String key);
/**
* 根据键判断缓存是否存在
*
* @param key 键
* @return
*/
boolean exists(String key);
/**
* 注入指定key生存时间
*
* @param key 值
* @param timeSecond 生存时间(秒)
* @return
*/
long expire(String key, int timeSecond);
/**
* 根据键删除对应键值
*
* @param key 键
* @return
*/
long deleteByKey(String key);
String getStringHash(String key);
Long setStringHash(String key, String value, int timeSeconds);
Long delHashValue(String key);
long setSet(String key, Set value, int cacheSeconds);
Set getSet(String key);
long setSetAdd(String key, String... value);
String getObjectListNew(String key);
long deleteByKeyPrefix(String keyPrefix);
long incr(String key);
}
4.启动项目的时候监听是否连接缓存成功
package com.test.demo.common.confige;
import com.test.demo.common.cache.CacheManageFactory;
import com.test.demo.common.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class ApplicationStartListener implements ApplicationListener {
private static final String QYPMS_START = "test";
protected Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
//初始化Redis连接
try {
CacheManageFactory.getInstance().set(QYPMS_START, true);
if (CacheManageFactory.getInstance().get(QYPMS_START).equals(true)) {
logger.info("redis连接成功!");
//初始化部门
} else {
logger.info("redis连接失败...请检查缓存是否开启");
}
} catch (Exception e) {
StringUtil.getStackMsg(e);
logger.info("redis连接失败...请检查缓存是否开启");
}
}
}
运行后结果
写个Controller类来测试
请求接口
然后redis查看数据
数据插如redis里面了
以上就是springboot集成redis,搭建缓存的过程