注明:本文章旨在整理近期开发中的心得,距离卓越还有很大差距,如果有问题可以评论,互相学习。
由于我在做某个系统,在设计的时候没有在mysql表中设计购物车数据库,而在微信小程序中,微信小程序自带的缓存StorageSync在我重新登录时缓存会清空,那么为了使购物车中的数据进行半持久化,抱着试一试的心态,决定使用redis来实现购物车缓存。
如果没法在springboot中连接linux中的redis,可以看我之前的blog:
springboot项目没法连接linux中的redis解决办法_Wannabe_hacker的博客-CSDN博客
一、maven中导入依赖
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>jcl-over-slf4j</groupId>
<artifactId>org.slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- https://mvnrepository.com/artifact/io.lettuce/lettuce-core -->
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</dependency>
</dependencies>
二、在application.properties中加入redis
由于虚拟机有问题,我就先用windows的redis进行测试,然后换用linux的redis就好,经过之前配置好redis之后,只需要在其中换一个ip就好了
# redis配置
spring.redis.database=9 # 这边用redis中哪个数据库都没关系
spring.redis.host=127.0.0.1
spring.redis.port=6379
额外需要配置的也可以进行配置
注意现在新的redis中lettuce代替jedis
三、编写RedisConfig.class进行配置
没什么好说的,网上代码通用
package com.xxxx.common;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
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.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.naming.event.ObjectChangeListener;
import java.net.UnknownHostException;
@Configuration
public class RedisConfig {
@Bean
@SuppressWarnings("all")
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(factory);// 配置连接工厂
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper objectMapper = new ObjectMapper();//自定义ObjectMapper
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会抛出异常
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
//String序列化配置
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
四、编写RedisUtils的工具类
由于redisTemplate的函数太麻烦了,为了简便用和redis-cli中同样的命令,我们这里用工具类封装,我这里的工具类也是网上找的,非原创,真的要自己写的话直接放弃, 太多了!
这个工具类不全,如果有缺失可以逐步增加,当然也可以用别人的,我在gitee上找到一个好用的,如果我下面这个工具类中没有的,我就去里面找
RedisUtil: 最全的Java操作Redis的工具类,使用StringRedisTemplate实现,封装了对Redis五种基本类型的各种操作!
我csdn中找到的工具类:
package com.xxxx.utils;
import java.util.*;
import java.util.concurrent.TimeUnit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
/**
* Redis工具类
*
* @author zlpt
* @date 2020年11月17日
*/
@Component
@Slf4j
public final class RedisUtils {
// 直接用RedisTemplate操作Redis,需要很多行代码,因此直接封装好一个RedisUtil,这样写代码更方便点。这个RedisUtil交给Spring容器实例化,使用时直接注解注入。
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// =============================common============================
/**
* 指定缓存失效时间
*
* @param 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;
}
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
*
* @param key ...表示可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取所有给定字段的值
* author: xu
* @param key
* @return
*/
public Map<Object, Object> hgetall(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(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 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(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 sSetAndTime(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 键
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @return
*/
public boolean lSet(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 lSet(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 value 值
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
五、编写Vo实体和Dto实体
由于数据库中没有表,我就不建正规实体了,直接写一个Dto实体,从前端传入数据,数据写进redis。然后写一个Vo实体,从redis中取到数据,然后返回给前端。
由于我们是一个设备租赁的demo,设备为Equipment,用户为User,设备租赁可以填写设备进场时间inTime,设备归还预期时间predictTime,租赁数量num
CartItemDto实体:
package com.xxxx.entity.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.xxxx.entity.Equipment;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class CartItemDto{
private static final long serialVersionUID = 1L;
private Integer userId;// 使用用户的Id
private Long equipmentId;//用户选择购物车中的设备
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date predictTime;//用户选择的预计时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date inTime;//用户选择的进场时间
private Integer num; //用户选择设备的数量
}
CartItemVo实体:
package com.xxxx.entity.vo;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.xxxx.entity.Equipment;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.Date;
@Data
@Accessors(chain = true)//链式编程
public class CartItemVo {
// private Integer userId;// 使用用户的Id
private Equipment equipment;//用户选择购物车中的设备
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date predictTime;//用户选择的预计时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date inTime;//用户选择的进场时间
private Integer num; //用户选择item的数量
}
六、写controller层来调用进行redis的crud操作
由于没有数据库表,懒得写service和serviceImp,直接写在controller中,不是很规范,但是可以看看代码怎么使用的。
package com.xxxx.controller;
import com.xxxx.common.Result;
import com.xxxx.entity.Contract;
import com.xxxx.entity.Equipment;
import com.xxxx.entity.dto.CartItemDto;
import com.xxxx.entity.vo.CartItemVo;
import com.xxxx.service.EquipmentService;
import com.xxxx.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* TODO 购物车类型缓存接口
*
* @author xu
* <br>CreateDate 2022/3/10 21:48
*
* 由于本系统没有购物车数据库,故我们将购物车存放在redis中
* 其中关联到的数据有 CartItemDto实体
*/
@RestController
@RequestMapping("/cart")
@Api(tags = "购物车模块 采用redis缓存") #swagger测试接口用的
public class CartController extends BaseController{
@Autowired
private EquipmentService equipmentService;
@Autowired
private RedisUtils redisUtils;
// 增加
// 选用设备添加到购物车
@ApiOperation(value = "选用设备添加到购物车")
@PostMapping("/addEquipmentToCart")
@ResponseBody
public Result<?> addEquipmentToCart(@RequestBody CartItemDto cartItemDto){
boolean hsetSuccessStatus = redisUtils.hset(cartItemDto.getUserId().toString(), cartItemDto.getEquipmentId().toString(), cartItemDto);
System.out.println(cartItemDto);
return Result.success();
}
// 查取用户对应redis中全部数据
// 从购物车缓存中取数据
@ApiOperation(value = "从购物车缓存中取数据")
@GetMapping("/getEquipmentInCartByUserId")
@ResponseBody
public Result<?> getEquipmentInCartByUserId(@RequestParam Integer userId){
// 创建一个CartItemDto的空对象 ,目的是用来接从redis取到的数据
CartItemDto cartItemDto;
// 从redis中根据用户Id获取到购物车里的数据
Map<Object, Object> userCartItems = redisUtils.hgetall(userId.toString());
// 创建一个数组将所有的Vo对象都接出来返回到前端
ArrayList<CartItemVo> cartItemVos = new ArrayList<>();
//遍历map中的值 每一个value都是一个CarItemDto对象
for (Object value : userCartItems.values()) {
// 为了获取到cartItem中的get方法,我们必须要将它强转成为一个CartItemDto来接住数据
cartItemDto= (CartItemDto) value;
// 这里好像之前写的有问题 要将Integer转换成为Long,这样才能传出去
Equipment equipment = equipmentService.equipmentDetail(cartItemDto.getEquipmentId());
// 这里vo对象接住Dto中的所有数据和equipment中的所有数据,然后返回给前端
// 注意!! 这里每一次循环都要new一个实例,会占用资源
CartItemVo cartItemVo= new CartItemVo();
// 在CartItemVo中定义了链式编程,这里就这么写了
cartItemVo.setEquipment(equipment).setNum(cartItemDto.getNum())
.setInTime(cartItemDto.getInTime()).setPredictTime(cartItemDto.getPredictTime());
cartItemVos.add(cartItemVo);
}
System.out.println("===============Vos对象=============="+cartItemVos);
return Result.success(cartItemVos);
}
// 修改
// 设备添加到购物车
@ApiOperation(value = "修改购物车数据")
@PutMapping("/updateEquipmentToCart")
@ResponseBody
public Result<?> updateEquipmentToCart(@RequestBody CartItemDto cartItemDto){
/* 修改的操作和增加的操作是一样的
* 由于我们目前存放购物车数据的方式是 hset userId:传入的userId 设备Id 购物车项Dto对象
* 我们对应redis中的东西来看就是 hset key:xx field value
* 我们重新hset一个相同key的相同field的值 , 那么它的value会变 也就是覆盖掉了
* */
redisUtils.hset(cartItemDto.getUserId().toString(),cartItemDto.getEquipmentId().toString(),cartItemDto);
System.out.println(cartItemDto);
return Result.success();
}
// 删除
// 选用设备从购物车删除
@ApiOperation(value = "选用设备从购物车删除")
@DeleteMapping("{userId}/{equipmentId}")
@ResponseBody
public Result<?> DeleteEquipmentFromCart(@PathVariable Integer userId , @PathVariable Long equipmentId){
redisUtils.hdel(userId.toString(),equipmentId.toString());
return Result.success();
}
}
来测试一下接口:
其他几个接口测试都成功了,但是我没有放进去因为忘记截图了!
好了这个redis的用法可能有点低级,但是确实获取到了数据!
完成接口的测试