package com.lsh.product.config.redis;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
* Description :〈jedis配置类〉
*
* @author white
* @create 2020/6/18
* @since 1.0.0
*/
@Slf4j
@Configuration
public class JedisPoolFactory {
private Logger logger = LoggerFactory.getLogger(JedisPoolFactory.class);
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.jedis.pool.max-active}")
private int maxActive;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis;
@Bean
public JedisPool generateJedisPoolFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(poolConfig, host, port, timeout, password);
logger.info("redis地址:" + host + ":" + port);
return jedisPool;
}
/**
* 重写Redis序列化方式,使用Json方式:
* 当我们的数据存储到Redis的时候,我们的键(key)和值(value)都是通过Spring提供的Serializer序列化到数据库的。RedisTemplate默认使用的是JdkSerializationRedisSerializer,StringRedisTemplate默认使用的是StringRedisSerializer。
* Spring Data JPA为我们提供了下面的Serializer:
* GenericToStringSerializer、Jackson2JsonRedisSerializer、JacksonJsonRedisSerializer、JdkSerializationRedisSerializer、OxmSerializer、StringRedisSerializer。
* 在此我们将自己配置RedisTemplate并定义Serializer。
*
* @param redisConnectionFactory
* @return
*/
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
// JdkSerializationRedisSerializer jdkSerializationRedisSerializer = new JdkSerializationRedisSerializer();
GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
// 设置值(value)的序列化采用FastJsonRedisSerializer。
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// 设置键(key)的序列化采用StringRedisSerializer。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
package com.lsh.product.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
/**
* 在字符串后边追加 字符串
* @param key
* @param appendValue
* @return
*/
public ValueOperations append(String key, String appendValue) {
ValueOperations operations = this.redisTemplate.opsForValue();
operations.append(key, appendValue);
return operations;
}
/**
* 缓存基本的对象,Integer、String、实体类等
* @param key 缓存的健值
* @param value 缓存的值
* @return 缓存的对象
*/
public ValueOperations setCacheObject(String key, T value) {
ValueOperations operations = this.redisTemplate.opsForValue();
operations.set(key, value);
return operations;
}
/**
* 缓存基本的对象,Integer、String、实体类等
* @param key 缓存的健值
* @param value 缓存的值
* @param timeout 时间
* @param timeUnit 时间颗粒度
* @return 缓存的对象
*/
public ValueOperations setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit) {
ValueOperations operations = this.redisTemplate.opsForValue();
operations.set(key, value, timeout, timeUnit);
return operations;
}
/**
* 缓存基本的对象,Integer、String、实体类等
* @param key 缓存的健值
* @param value 缓存的值
* @param timeout 时间
* @return 缓存的对象
*/
public ValueOperations setCacheObject(String key, T value, Duration timeout) {
ValueOperations operations = this.redisTemplate.opsForValue();
operations.set(key, value, timeout);
return operations;
}
/**
* 获得缓存的基本对象。
*
* @param key 缓存键值
* @return 缓存键值对应的数据
*/
public T getCacheObject(String key) {
ValueOperations operation = this.redisTemplate.opsForValue();
return operation.get(key);
}
/**
* 设置过期时间
* @param key key值
* @param timeout 时间
* @param timeUnit 时间单位
* @return
*/
public Boolean setExpire(String key, Long timeout, TimeUnit timeUnit) {
return this.redisTemplate.expire(key, timeout, timeUnit);
}
/**
* 删除单个对象
* @param key
*/
public void deleteObject(String key) {
this.redisTemplate.delete(key);
}
/**
* 删除集合对象
* @param collection
*/
public void deleteObject(Collection collection) {
this.redisTemplate.delete(collection);
}
/**
* 缓存List数据
*
* @param key 缓存的键值
* @param dataList 待缓存的List数据
* @return 缓存的对象
*/
public ListOperations setCacheList(String key, List dataList) {
ListOperations listOperations = this.redisTemplate.opsForList();
if (null != listOperations) {
int size = dataList.size();
for (int i = 0; i < size; i++) {
listOperations.leftPush(key, dataList.get(i));
}
}
return listOperations;
}
/**
* 获得缓存的list对象
*
* @param key 缓存的键值
* @return 缓存键值对应的数据
*/
public List getCacheList(String key) {
List dataList = new ArrayList<>();
ListOperations listOperations = this.redisTemplate.opsForList();
Long size = listOperations.size(key);
for (long i = 0; i < size; i++) {
dataList.add(listOperations.index(key, i));
}
return dataList;
}
/**
* 缓存Set
*
* @param key 缓存键值
* @param dataSet 缓存的数据
* @return 缓存数据的对象
*/
public BoundSetOperations setCacheSet(String key, Set dataSet) {
BoundSetOperations setOperations = this.redisTemplate.boundSetOps(key);
Iterator iterable = dataSet.iterator();
while (iterable.hasNext()) {
setOperations.add(iterable.next());
}
return setOperations;
}
/**
* 获得缓存的set
*
* @param key
* @return
*/
public Set getCacheSet(String key) {
Set dataSet = new HashSet<>();
BoundSetOperations setOperations = this.redisTemplate.boundSetOps(key);
Long size = setOperations.size();
for (long i = 0; i < size; i++) {
dataSet.add(setOperations.pop());
}
return dataSet;
}
/**
* 缓存Map
*
* @param key
* @param dataMap
* @return
*/
public void hashPutAll(String key, Map dataMap) {
this.redisTemplate.opsForHash().putAll(key, dataMap);
}
/**
* 在hash中新增一个值
* @param key
* @param field
* @param value
*/
public void hashPut(String key, String field, Object value) {
this.redisTemplate.opsForHash().put(key, field, value);
}
/**
* 当field不存在时put
* @param key
* @param field
* @param value
*/
public void hashPutIfAbsent(String key, String field, Object value) {
this.redisTemplate.opsForHash().putIfAbsent(key, field, value);
}
/**
* 获得缓存的Map
*
* @param key
*/
public Map hashGetAll(String key) {
return this.redisTemplate.opsForHash().entries(key);
}
/**
* 获取键值为key的hash中的field字段的值
* @param key
* @param field
*/
public Object hashGet(String key, String field) {
return this.redisTemplate.opsForHash().get(key, field);
}
/**
* 获取键值为key的hash表中所有字段
* @param key
*/
public Set hashKeys(String key) {
return this.redisTemplate.opsForHash().keys(key);
}
/**
* 获取键值为key的hash表中所有value
* @param key
*/
public List
使用
public String hello(){
// stringRedisTemplate.opsForValue().set("b","cccccc");
EsMember es = new EsMember();
es.setId(1);
es.setEmail("[email protected]");
redisUtil.setCacheObject("b",JSONObject.toJSONString(es));
System.out.println("------"+redisUtil.getCacheObject("b").toString());
EsMember es2 = JSONObject.parseObject(redisUtil.getCacheObject("b").toString(),EsMember.class);
System.out.println(es2);
return "hello";
}