本篇文章记录一下springboot 操作redis
一、加载redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.4.0</version>
</dependency>
二、添加redis配置(application.yml){此处只是简单的配置}
redis:
database: 0
host: 127.0.0.1
port: 6379
password: 123456
三、创建编写redisConfig
package com.zhangxian.pay.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
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 org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* @program: com.zhangxian.pay.config
* @author: zwx
* @create: 2020-12-08 15:52
**/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory)
{
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// todo 替换默认序列化(默认的序列化使用的是JDK序列化)
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(mapper);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
四、创建redis操作类 {以下操作并不全面,各位可以自行扩展}
package cn.zhangxian.pay.util.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @program: com.zhangxian.pay.util.redis
* @author: zwx
* @create: 2020-12-08 17:33
**/
// todo @Component 将一个普通的javaBean 实例化到spring容器中
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 设置过期时间
* @param key redis key值
* @param time 过期时间
* @return
*/
public boolean expire(String key, long time)
{
try {
if ( time > 0 ) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
*获取过期时间
* @param key redis key
* @return
*/
public long getExpire(String key)
{
try {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ====================================================== get =====================================================//
/**
* 根据key获取值
* @param key
* @return
*/
public Object StringGet(String key)
{
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 设置值
* @param key
* @param value
* @return
*/
public boolean StringSet(String key, Object value)
{
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 设置值并设置过期时间 如果过期时间大于0 则设置过期时间
* @param key
* @param value
* @param time
* @return
*/
public boolean StringExpireSet(String key, Object value, long time)
{
try {
if ( time > 0 ) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
StringSet(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 通过key删除值
* @param key
*/
public void StringDelete(String... key)
{
if ( key != null && key.length > 0 ) {
if ( key.length == 1 ) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
}
}
}
// ====================================================== hash ===================================================//
/**
* 获取hash值
* @param key hash大key
* @param item hash 小key
* @return
*/
public Object HashGet(String key, String item)
{
return redisTemplate.opsForHash().get(key, item);
}
/**
* 设置hash值
* @param key hash 值的大key
* @param item hash 值的小key
* @param value hash 存储的值
* @return
*/
public boolean HashSet(String key, String item, Object value)
{
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 设置hash值并设置过期时间 如果过期时间大于0则设置过期时间
* @param key
* @param item
* @param value
* @param time
* @return
*/
public boolean HashExpireSet(String key, String item , Object value, long time)
{
try {
redisTemplate.opsForHash().put(key, item, value);
if ( time > 0 ) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash 值
* @param key
* @param item
*/
public void HashDelete(String key, Object... item)
{
redisTemplate.opsForHash().delete(key, item);
}
// ====================================================== set ====================================================//
/**
* 设置 set 值
* @param key
* @param values
* @return
*/
public long SetSet(String key, Object... values)
{
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 设置set值 并且设置过期时间
* @param key
* @param time
* @param values
* @return
*/
public long SetExpireSet(String key, long time, Object... values)
{
try {
Long count = redisTemplate.opsForSet().add(key, values);
if ( time > 0 ) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 删除set值
* @param key
* @param values
* @return
*/
public long SetDelete(String key, Object... values)
{
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过key获取set值
* @param key
* @return
*/
public Set<Object> SetGet(String key)
{
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// ====================================================== list ===================================================//
/**
* list 通过key获取值 如果 start = 0 end = -1 查询的所有的数据
* @param key 需要查询的key值
* @param start 开始数据
* @param end 结束数据
* @return
*/
public List<Object> ListGet(String key, long start, long end)
{
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 设置list值
* @param key 键值
* @param value 值
* @return
*/
public boolean ListSet(String key, Object value)
{
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* list 设置值 并且设置过期时间
* @param key 键值
* @param value 值
* @param time 过期时间
* @return
*/
public boolean ListExpireSet(String key, Object value, long time)
{
try {
redisTemplate.opsForList().rightPush(key, value);
if ( time > 0 ) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除list值
* @param key 键值
* @param count 删除的数量
* @param values 删除的值
* @return
*/
public long ListDelete(String key, long count, Object values)
{
try {
Long removeCount = redisTemplate.opsForList().remove(key, count, values);
return removeCount;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
五、添加service
package cn.zhangxian.pay.service.redis;
/**
* @program: com.zhangxian.pay.service.redis
* @author: zwx
* @create: 2020-12-09 09:31
**/
public interface IGoodsRedisService {
public void addGoodsString(String key, Object value);
public void addGoodsHash(String key, String item, Object value);
public Object getGoodsHash(String key, String item);
}
六、实现service接口
package cn.zhangxian.pay.service.impl.redis;
import cn.zhangxian.pay.service.redis.IGoodsRedisService;
import cn.zhangxian.pay.util.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @program: com.zhangxian.pay.service.impl.redis
* @author: zwx
* @create: 2020-12-09 09:32
**/
@Service("GoodsRedis")
public class GoodsRedis implements IGoodsRedisService {
@Autowired
private RedisUtil redisUtil;
@Override
public void addGoodsString(String key, Object value)
{
redisUtil.StringSet(key, value);
}
@Override
public void addGoodsHash(String key, String item, Object value)
{
redisUtil.HashSet(key, item, value);
}
@Override
public Object getGoodsHash(String key, String item) {
return redisUtil.HashGet(key, item);
}
}
六、控制器中使用
goodsRedis.addGoodsString("goods", "这是一个商品的String缓存redis");
GoodsSolrEntity goodsSolrEntity = new GoodsSolrEntity();
goodsSolrEntity.setId("8");
goodsSolrEntity.setCategory_id((long) 1);
goodsSolrEntity.setGoods_name("苹果2");
goodsSolrEntity.setGoods_img("11111111");
goodsSolrEntity.setGoods_thumb("["+"11111"+",111111"+"]");
goodsSolrEntity.setIs_hot((long) 1);
goodsSolrEntity.setIs_sale((long) 1);
goodsSolrEntity.setIs_new((long) 1);
goodsSolrEntity.setMarket_price("100");
goodsSolrEntity.setShop_price("100");
goodsSolrEntity.setGoods_attr_list("[]");
goodsSolrEntity.setDesc("描述");
goodsSolrEntity.setShelves_at("111111111111");
goodsSolrEntity.setCreated_at("2020-12-01 14:21:55");
goodsSolrEntity.setUpdated_at("2020-12-01 14:21:55");
goodsSolrEntity.setStore_id((long) 3);
String goods = JSON.toJSONString(goodsSolrEntity);
// 添加hash至
goodsRedis.addGoodsHash("goods_hash", "goods", goods);
// 获取
Object goodsInfo = goodsRedis.getGoodsHash("goods_hash", "goods");
System.out.println(goodsInfo);