spring boot
具体步骤如下:
1,准备好spring boot工程
2,准备好Redis服务器
3,添加相关依赖,可以百度这里不写了
4,编写Redis需要用的工具类 RedisConfig、 RedisUtil.java和RedisDao.java。
RedisConfig
package com.hdys.www.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.hdys.www.controller.UserController;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
private final Logger log = LoggerFactory.getLogger(RedisConfig.class);
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis;
@Bean
public JedisPool redisPoolFactory() {
log.info("JedisPool注入成功!!");
log.info("\"redis地址:\" + host + \":\" + port");
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout);
return jedisPool;
}
}
RedisUtil.java
package com.hdys.www.util;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Client;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.util.Slowlog;
@Component
public class RedisUtil {
@Autowired
JedisPool jedisPool;
// 获取redis 服务器信息
public String getRedisInfo() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Client client = jedis.getClient();
client.info();
String info = client.getBulkReply();
return info;
} finally {
// 返还到连接池
jedis.close();
}
}
// 获取日志列表
public List
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
List
return logList;
} finally {
// 返还到连接池
jedis.close();
}
}
// 获取日志条数
public Long getLogsLen() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
long logLen = jedis.slowlogLen();
return logLen;
} finally {
// 返还到连接池
jedis.close();
}
}
// 清空日志
public String logEmpty() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.slowlogReset();
} finally {
// 返还到连接池
jedis.close();
}
}
// 获取占用内存大小
public Long dbSize() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
// TODO 配置redis服务信息
Client client = jedis.getClient();
client.dbSize();
return client.getIntegerReply();
} finally {
// 返还到连接池
jedis.close();
}
}
}
RedisDao.java
package com.hdys.www.redisDao;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.hdys.www.pojo.ProductList;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@Component
public class RedisDao {
//private final static JedisPool jedisPool;
@Autowired
JedisPool jedisPool;
private Jedis jedis;
/* @Autowired
public JedisPool jedisPool;*/
// 创建一个schema用来序列化
private RuntimeSchema
/**
* 构造方法
*
* @param ip
* 访问的ip
* @param port
* 访问的端口
*/
/*public RedisDao(String uri, int port) {
jedisPool = new JedisPool(uri, port);
}*/
/* static {
//RedisDao redisDao = new RedisDao("localhost", 6379);
jedisPool = new JedisPool("localhost", 6379);
}
*/
public ProductList getProductInfo(int ProductId) {
// redis操作
try {
Jedis jedis = jedisPool.getResource();
try {
// 在redis中存放时,key的书写规则,官方推荐,对象:对象属性
String key = "Product" + ProductId;
// 自定义序列化
// 在redis中获取的值一定是一个字节数组,需要通过反序列化转换成java对象
byte[] bytes = jedis.get(key.getBytes());
if (bytes != null) {
// 获取一个空对象
ProductList productList = schema.newMessage();
// 反序列化后放置在productList中
ProtostuffIOUtil.mergeFrom(bytes, productList, schema);
return productList;
}
} finally {
jedis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String putProductInfo(ProductList productList) {
try {
Jedis jedis = jedisPool.getResource();
try {
// 通过对应的键存放user对象,建的ID唯一,一般使用ID
String key = "Product" + productList.getSid();
// 自定义序列化操作,利用protostuff将对象序列化成字节数组
byte[] bytes = ProtostuffIOUtil.toByteArray(productList, schema,
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
// 缓存时间1小时,缓存的时间是用秒来计的
int timeout = 60 * 60;
jedis.set("ceshi", "succcess");
// 在redis中存放这个对象
return jedis.setex(key.getBytes(), timeout, bytes);
}catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
5:配置文件application.properties
#redis
spring.redis.host= localhost
spring.redis.port= 6379
spring.redis.pool.max-idle= 8
spring.redis.pool.min-idle= 0
spring.redis.pool.max-active= 8
spring.redis.pool.max-wait= -1
spring.redis.timeout= 0
6:简单使用
public ProductList getProductInfo(int sid) {
try {
productInfo = redisDao.getProductInfo(sid);
//如果不存在,那就在缓存中放置信息
if(productInfo == null)
{
//先取到
productInfo=productListMapper.selectProductsInfo(sid);
//put
redisDao.putProductInfo(productInfo);
}else{
return productInfo;
}
} catch (Exception e) {
log.info("xxxx" + e);
}
return productInfo;
}
ssm配置redis主要方法:
1:spring配置文件applicationContext.xml
2:相关工具类
me.xxxx.www.common.redis.RedisSetting 对应spring配置文件
public class RedisSetting {
public RedisSetting(){
}
//
//这里改成自己的,其实就是通过反射获取你xml里的配置好的那个bean,对应代码在下面
}
SpringUtil.java
/**
* 从Spring中获取对应bean
*/
public class SpringUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
SpringUtil.applicationContext = context;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
}
//
3:JedisUtil.java
package me.uniauto.www.common.redis;
import me.xxxx.www.common.SerializeUtil;
import me.xxxx.www.common.redis.factory.JedisAbstractFactory;
import me.xxxx.www.common.util.CommonUtils;
import redis.clients.jedis.Jedis;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* redis公共处理插件类
*/
public final class JedisUtil {
private JedisAbstractFactory jedisFactory;
public JedisUtil(JedisAbstractFactory jedisFactory){
this.jedisFactory=jedisFactory;
}
/**
* 获取指定模式的 key 列表
* @param pattern
* @return
* @throws Exception
*/
public Set
Jedis jedis=jedisFactory.getJedis();
try{
Set
return keys;
}catch(Exception ex){
throw new Exception("获取Redis中指定模式的key列表时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 删除指定key
* @param key
* @throws Exception
*/
public void del(String key) throws Exception{
Jedis jedis=jedisFactory.getJedis();
try{
del(jedis, key);
}catch(Exception ex){
throw new Exception("删除Redis中指定key时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 删除存储的对象
* @param key
* @throws Exception
*/
public void delObj(String key) throws Exception{
Jedis jedis=jedisFactory.getJedis();
try{
delObj(jedis,key);
}catch(Exception ex){
throw new Exception("删除Redis中存储的对象时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 删除一组存储的对象
* @param keys
* @throws Exception
*/
public void delObjList(List
Jedis jedis=jedisFactory.getJedis();
try{
for(String key :keys){
delObj(jedis,key);
}
}catch(Exception ex){
throw new Exception("删除Redis中存储的多个对象时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 从redis中删除指定key
* @param jedis
* @param key
*/
private void del(Jedis jedis, String key){
if(jedis!=null){
if(jedis.exists(key)){
jedis.del(key);
}
}
}
/**
* 从redis中删除存储的对象
* @param jedis
* @param key
*/
private void delObj(Jedis jedis,String key){
if(jedis!=null){
byte[] byteKey=key.getBytes();
if(jedis.exists(byteKey)){
jedis.del(byteKey);
}
}
}
/**
* 将对象序列化后存入Redis
* @param key
* @param obj
* @throws Exception
*/
public void setObj(String key, Object obj) throws Exception{
Jedis jedis=jedisFactory.getJedis();
try{
jedis.set(key.getBytes(), SerializeUtil.serialize(obj));
}catch(Exception ex){
throw new Exception("将对象存入Redis中时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 将一组对象序列化后存入Redis
* @param keyVals
* @throws Exception
*/
public void setObj(Map
Jedis jedis=jedisFactory.getJedis();
try{
for(String key:keyVals.keySet()){
jedis.set(key.getBytes(), SerializeUtil.serialize(keyVals.get(key)));
}
}catch(Exception ex){
throw new Exception("将一组对象存入Redis中时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
//string、对象、map
/**
* 设置字符串值存入redis
* @param key
* @param value
* @throws Exception
*/
public void set(String key, String value) throws Exception{
Jedis jedis=jedisFactory.getJedis();
try{
del(jedis,key);
jedis.set(key, value);
}catch(Exception ex){
throw new Exception("将字符串存入Redis时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 批量设置一系列字符串值
* @param map
* @throws Exception
*/
public void set(Map
Jedis jedis=jedisFactory.getJedis();
try{
for(String key:map.keySet()){
del(jedis,key);
jedis.set(key, map.get(key));
}
}catch(Exception ex){
throw new Exception("在Redis中批量设置一系列字符串值时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 设置Hash值
* @param key
* @param value
* @throws Exception
*/
public void hmset(String key,Map
Jedis jedis=jedisFactory.getJedis();
try{
del(jedis,key);
jedis.hmset(key, value);
}catch(Exception ex){
throw new Exception("在Redis中设置Hash值时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 批量设置Hash值
* @param map
* @throws Exception
*/
public void hmset(Map
Jedis jedis=jedisFactory.getJedis();
try{
for(String key:map.keySet()){
del(jedis,key);
jedis.hmset(key, map.get(key));
}
}catch(Exception ex){
throw new Exception("在Redis中批量设置Hash值时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 将指定对象存入Redis中
* @param
* @param key
* @param t
* @throws Exception
*/
public
Map
hmset(key,map);
}
/**
* 批量将对象放入redis
* @param
* @param tMap
* @throws Exception
*/
public
Jedis jedis=jedisFactory.getJedis();
try{
for(String key:tMap.keySet()){
Map
del(jedis,key);
jedis.hmset(key, objMap);
}
}catch(Exception ex){
throw new Exception("批量将对象以Hash值的方式放入Redis时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 获取字符串的值
* @param key
* @return
* @throws Exception
*/
public String get(String key) throws Exception{
Jedis jedis=jedisFactory.getJedis();
try{
String value=jedis.get(key);
return value;
}catch(Exception ex){
throw new Exception("获取Redis中字符串的值时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 获取存储在Redis中的序列化的对象
* @param
* @param key
* @param clazz
* @return
* @throws Exception
*/
public
Jedis jedis=jedisFactory.getJedis();
try{
byte[] val=jedis.get(key.getBytes());
T t=null;
if(val!=null){
t=SerializeUtil.unserialize(val, clazz);
}
return t;
}catch(Exception ex){
throw new Exception("获取存储在Redis中的序列化的对象时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 获取一组存储在Redis中的序列化的对象
* @param
* @param keys
* @param clazz
* @return
* @throws Exception
*/
public
Jedis jedis=jedisFactory.getJedis();
try{
Map
for(String key:keys){
byte[] val=jedis.get(key.getBytes());
T t=null;
if(val!=null){
t=SerializeUtil.unserialize(val, clazz);
}
vals.put(key, t);
}
return vals;
}catch(Exception ex){
throw new Exception("获取一组存储在Redis中的序列化的对象时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 获取Hash值
* @param key
* @return
* @throws Exception
*/
public Map
Jedis jedis=jedisFactory.getJedis();
try{
if(!jedis.exists(key)){
return null;
}
Map
return value;
}catch(Exception ex){
throw new Exception("获取Redis中的Hash值时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 获取Hash结构的部分值
* @param key
* @param fields
* @return
* @throws Exception
*/
public List
Jedis jedis=jedisFactory.getJedis();
try{
if(!jedis.exists(key)){
return null;
}
List
return value;
}catch(Exception ex){
throw new Exception("获取Redis中Hash结构的部分值时发生异常",ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 获取指定对象的指定字段值
* @param
* @param key
* @param clazz
* @param fields
* @return
* @throws Exception
*/
public
List
if(vals==null){
return null;
}
HashMap
for(int i=0;i
map.put(fields[i], vals.get(i));
}
T t=CommonUtils.mapRelationObj((HashMap
return t;
}
/**
* 获取指定对象
* @param
* @param key
* @param clazz
* @return
* @throws Exception
*/
public
Map
if(map==null){
return null;
}
T t=CommonUtils.mapRelationObj((HashMap
return t;
}
/**
* 获取value 为 list的方法
*/
public List
Jedis jedis=jedisFactory.getJedis();
try{
if(!jedis.exists(key)){
return null;
}
List
//LLEN key获取长度
long stop = jedis.llen(key);
//LRANGE key start stop 获取数据
if(stop > 0){
strList = jedis.lrange(key, 0, stop);
}
return strList;
}catch(Exception ex){
throw new Exception("获取Redis中的list值时发生异常", ex);
}finally{
jedisFactory.close(jedis);
}
}
/**
* 设置 list
* @param
* @param key
*/
public
Jedis jedis = jedisFactory.getJedis();
try {
jedis.set(key.getBytes(), CommonUtils.serialize(list));
} catch(Exception ex){
throw new Exception("获取Redis中的list值时发生异常", ex);
} finally{
jedisFactory.close(jedis);
}
}
/**
* 获取list
* @param
* @param key
* @return list
*/
public
Jedis jedis = jedisFactory.getJedis();
try {
if(jedis == null || !jedis.exists(key.getBytes())){
return null;
}
byte[] in = jedis.get(key.getBytes());
List
return list;
} catch(Exception ex){
throw new Exception("获取Redis中的list值时发生异常", ex);
} finally{
jedisFactory.close(jedis);
}
}
}
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
me.xxxx.www.common.SerializeUtil;
public class SerializeUtil {
/**
* 序列化对象
* @param object
* @return
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
}finally{
try{
if(oos!=null){
oos.close();
}
if(baos!=null){
baos.close();
}
}catch(Exception ex){
}
}
return null;
}
/**
* 反序列对象
* @param bytes
* @return
*/
public static
ByteArrayInputStream bais = null;
ObjectInputStream ois =null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
Object obj= ois.readObject();
T t=clazz.cast(obj);
return t;
} catch (Exception e) {
}finally{
try{
bais.close();
ois.close();
}catch(Exception ex){
}
}
return null;
}
}
me.xxxx.www.common.redis.factory.JedisAbstractFactory;
import redis.clients.jedis.Jedis;
/**
* redis工厂
*/
public abstract class JedisAbstractFactory {
public abstract Jedis getJedis() throws Exception;
public void close(final Jedis jedis){
JedisOriginalFactory.close(jedis);
}
}
me.xxxx.www.common.util.CommonUtils;
/**
* 将对象转换成Map
*/
public static
Map
Class clazz = t.getClass();
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] propertyDescriptors = beanInfo
.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (key.compareToIgnoreCase("class") == 0) {
continue;
}
Method getter = property.getReadMethod();
Object value = getter != null ? getter.invoke(t) : "";
map.put(key, String.valueOf(value));
}
return map;
}
/**
* 将Map对象映射为指定对象
*
* @param
* @param map
* @param clazz
* @return
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static
Class
T obj = clazz.newInstance();
Set
Method[] methods = clazz.getMethods();
for (Map.Entry
String key = entry.getKey();
String value = entry.getValue();
for (Method method : methods) {
if (StringUtils.equals(
method.getName(),
"set" + key.substring(0, 1).toUpperCase()
+ key.substring(1))) {
// System.out.println(method.getName());
Class[] methodParam = method.getParameterTypes();
// System.out.println(methodParam[0].getName());
if (methodParam[0] == String.class) {
method.invoke(obj, value);
} else if (methodParam[0] == Integer.class
|| methodParam[0] == int.class) {
method.invoke(obj, Integer.parseInt(NumberUtils
.isNumber(value) ? value : "-1"));
} else if (methodParam[0] == Date.class) {
if (null != value && !"null".equals(value)) {
method.invoke(obj, new SimpleDateFormat(
"EEE MMM dd HH:mm:ss zzz yyyy", Locale.US)
.parse(value));
}
} else if (methodParam[0] == BigDecimal.class) {
if (null != value && !"null".equals(value)) {
method.invoke(obj, new BigDecimal(value));
}
} else {
throw new Exception("暂不支持的类型,请添加" + methodParam[0]
+ "类型的支持");
}
}
}
}
return obj;
}
public static byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] rv = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(value);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
try {
if (os != null) {
os.close();
}
if (bos != null) {
bos.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}
public static Object deserialize(byte[] in) {
Object rv = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
rv = is.readObject();
is.close();
bis.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
if (bis != null) {
bis.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}
4:使用方法参照boot