前言
1、
前段时间,做过一个项目,一开始甲方给的需求文档里没有说明数据存储用什么数据库,因为我也做过甲方的其他项目都是用的MySQL,所以这次我也就默认使用MySQL了。
2、
就一个电量电能统计分析工具,功能也很简单,做完了之后甲方跟我说这个工具是要可以在任意一台电脑上运行的,开发者的电脑安装了jdk和mysql可以运行,但是普通用户肯定不可能都给他们装上jdk和mysql吧,然后叫我看一下要怎么解决,数据存储不使用mysql。最后我就干脆把mysql改成redis。(因为之前对redis的使用一直都停留在配合shiro做权限控制,对于它单独像mysql一样持久化存储数据还是云里雾里的。网上看了一些案例大都不全,可能对于刚接触redis的小伙伴来说不太友好,特此整理写了个完整齐全的案例。)
3、
改完之后项目打包成jar包,将redis服务整个文件夹 、 jdk1.8里面的jre文件夹 、前端打包的exe程序 放在和jar包同一目录下,并且使用vbs脚本,同时启动redis-service、jar包、exe程序。只要不在任务管理器中将redis-service和jar结束进程,后续要使用这个工具时,只需要双击启动exe程序即可。
这样即使电脑没有jdk环境和redis服务,也可以运行这个工具。有个缺点就是这工具实在是大,前端打包出来的exe就有两百兆,再加上jre也有一百八十兆,加上jar包六十兆,总共就有四百多兆了。。。
4、
后面我突然想到,其实可以把jar包和jdk环境用exe4j打包成exe程序的,就不用另外将jre文件夹放到里面了 。不过项目交都交了,甲方那边也没说啥,也就懒得跟他们说了。
这个电量电能统计分析工具不适合作为案例来写,就整理了一下,写了个更易懂明了的例子,实际项目中可以按照这种方式拓展业务。
一、依赖
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- @ConfigurationProperties 注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- cache缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- gson:redis存取数据格式化 -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.9</version>
</dependency>
<!-- StringUtilS工具 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
二、启动类
//不使用mysql数据库,所以排除数据源
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableCaching
三、yml配置
server:
port: 8082
spring:
cache:
type: redis
redis:
host: localhost
port: 6379
password: 123456
database: 0
四、RedisConfig配置
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.*;
import java.lang.reflect.Method;
import java.net.UnknownHostException;
/**
* @author fuHua
* @date 2021年06月17日 14:31
*/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
/*
* 定义缓存数据 key 生成策略的bean 包名+类名+方法名+所有参数
*/
@Bean
public KeyGenerator wiselyKeyGenerator(){
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
//设置CacheManager的值序列化方式为json序列化
RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
.fromSerializer(jsonSerializer);
RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig()
.serializeValuesWith(pair);
//我们需要redis中的数据永久存储,所以不设置过期时间
// defaultCacheConfig.entryTtl(Duration.ofSeconds(1800));
//初始化RedisCacheManager
return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
}
/**
* redis序列化
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
//我们为了自己开发使用方便,一般使用<String, Object>类型
RedisTemplate<String, Object> template = new RedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
//序列化配置
//json序列化
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om=new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//String序列化
StringRedisSerializer stringRedisSerializer=new StringRedisSerializer();
//key使用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
//hash的key也使用String序列化
template.setHashKeySerializer(stringRedisSerializer);
//value使用json序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
//hash的value使用json序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
五、GsonUtil 数据格式化
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* 数据格式化:
* 数据以json字符串的方式存储;
* 再通过json字符串和实体类.class进行解析,返回实体类对象
* @author fuHua
* @date 2021年06月17日
*/
public class GsonUtil {
/**
* 存储数据
* @param object 需要存储的对象
* @return json字符串
*/
public static String object2Json(Object object) {
Gson gson = new GsonBuilder().create();
return gson.toJson(object);
}
/**
* 解析数据
* @param json json字符串
* @param clazz 返回的实体类的class对象
* @param <T>
* @return
*/
public static <T> T json2Object(String json, Class<T> clazz) {
Gson gson = new GsonBuilder().create();
return gson.fromJson(json, clazz);
}
}
六、RedisUtil(需要存取哪种数据类型,调用对应的存取方法)
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* redis工具类
*/
@Component
public class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
*/
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 可以传一个值 或多个
*/
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));
}
}
}
/**
* 普通缓存获取
* @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)
*/
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)
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().decrement(key,delta);
// return redisTemplate.opsForValue().increment(key, -delta);
}
public long strLen(String key){
return redisTemplate.opsForValue().get(key).toString().length();
}
/*
* 追加字符
* @param key 键
* @param str 要追加的字符
* */
public boolean append(String key,String str){
try {
redisTemplate.opsForValue().append(key,str);
return true;
}catch (Exception e){
return false;
}
}
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key 键
* @param map 对应多个键值
*/
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)
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
/**
* 根据key获取Set中的所有值
* @param key 键
*/
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 键
*/
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缓存的内容
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
*/
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 键
*/
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倒数第二个元素,依次类推
*/
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 值
*/
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 时间(秒)
*/
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;
}
}
}
七、使用
1、User实体类
@Data
public class User implements Serializable {
private Integer id;
private String name;
private String password;
private String dept;
public User(Integer id, String name, String password, String dept) {
this.id = id;
this.name = name;
this.password = password;
this.dept = dept;
}
}
2、UserService
import com.entity.User;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.util.GsonUtil;
import com.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.util.*;
/**
* @author fuHua
* @date 2021年06月17日
*/
@Service
@CacheConfig(cacheNames = "userService")
public class UserService {
@Autowired
private RedisUtil redisUtil;
/**
* 根据id排序
*/
public List<User> sortListById(List<User> list){
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
//升序
return o1.getId().compareTo(o2.getId());
}
});
return list;
}
/**
* 读取redis中,key为user的数据,并将每一条数据解析为user实体,添加到list中,返回给前端
* @param name 查询条件
* @param dept 查询条件
* @return
*/
public List<User> userList(String name,String dept){
List<User> list = new ArrayList<>();
List<User> newList = new ArrayList<>();
Map<Object, Object> map = redisUtil.hmget("user");
for (Object o: map.keySet()) {
User user = GsonUtil.json2Object(map.get(o).toString(), User.class);
list.add(user);
}
/**
* 根据姓名或部门筛选数据:
* redis中不能直接根据条件查询,只能先把全部数据获取然后再进行筛选
*/
if (StringUtils.isNotBlank(name) || StringUtils.isNotBlank(dept)){
for (User user : list) {
if (StringUtils.isNotBlank(name)) {
//精准查询
/*if (user.getName().equals(name)){
newList.add(user);
}*/
//模糊查询
if (user.getName().indexOf(name) != -1){
newList.add(user);
}
}
if (StringUtils.isNotBlank(dept)) {
/*if (user.getDept().equals(dept)){
newList.add(user);
}*/
if (user.getDept().indexOf(dept) != -1){
newList.add(user);
}
}
}
}else {
newList = list;
}
//返回排序后的数据
return sortListById(newList);
}
/**
* list分页
*/
public PageInfo<User> pageList(String name,String dept,Integer pageSize,Integer pageNum){
Page<User> page = new Page<>(pageNum, pageSize);
List<User> list = userList(name, dept);
int total = list.size();
page.setTotal(total);
int startIndex = (pageNum - 1) * pageSize;
int endIndex = Math.min(startIndex + pageSize, total);
if (total > startIndex) {
page.addAll(list.subList(startIndex, endIndex));
}
return new PageInfo<>(page);
}
/**
* 根据id获取用户
*/
public User getUserById(Integer id){
String hget = (String)redisUtil.hget("user", id.toString());
return GsonUtil.json2Object(hget, User.class);
}
/**
* 新增或修改数据
*/
public void createOrUpdate(User user){
Map<String, Object> map = new HashMap<>();
String id = GsonUtil.object2Json(user.getId());
String info = GsonUtil.object2Json(user);
map.put(id,info);
redisUtil.hmset("user",map);
}
/**
* 批量添加/修改用户
*/
public void batchCreateOrUpdate(){
List<User> list = list();
for (User user : list) {
createOrUpdate(user);
}
}
/**
* 根据id删除数据
*/
public void delete(Integer id){
redisUtil.hdel("user", id.toString());
}
public List<User> list(){
List<User> list = new ArrayList<>();
User user1 = new User(11,"琪亚娜","123456","打手部");
User user2 = new User(12,"雷电芽衣","888888","打手部");
User user3 = new User(13,"德莉莎","7777777","财务部");
User user4 = new User(14,"姬子","wwwwww","行政部");
User user5 = new User(15,"符华","666666","打手部");
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
list.add(user5);
return list;
}
/**
* 存储整个list对象
*/
public void saveList(){
String s = GsonUtil.object2Json(list());
redisUtil.lSet("list", s);
}
/**
* 读取list对象
*/
public List<User> getList(){
List<Object> list = redisUtil.lGet("list", 0, -1);
List<User> dataList = new ArrayList<>();
Gson gson = new GsonBuilder().create();
Type type = new TypeToken<List<User>>() {
}.getType();
for (Object o : list) {
String str = (String)o;
List<User> l = gson.fromJson(str, type);
dataList.addAll(l);
}
return dataList;
}
}
3、UserController
package com.controller;
import com.entity.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* @author fuHua
* @date 2021年06月17日
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 用户列表,不分页
*/
@GetMapping("/list")
public Map<String,Object> list(String name,String dept){
Map<String,Object> map = new HashMap<>();
map.put("list",userService.userList(name,dept));
return map;
}
/**
* 用户列表,分页
*/
@GetMapping("/page")
public Map<String,Object> page(String name,String dept,Integer pageSize,Integer pageNum){
Map<String,Object> map = new HashMap<>();
map.put("page",userService.pageList(name,dept,pageSize,pageNum));
return map;
}
/**
* 根据id获取用户
*/
@GetMapping("/getUserById/{id}")
public Map<String,Object> getUserById(@PathVariable("id") Integer id){
Map<String,Object> map = new HashMap<>();
map.put("user",userService.getUserById(id));
return map;
}
/**
* 新增/修改用户
*/
@PostMapping("/createOrUpdate")
public String createOrUpdate(User user){
userService.createOrUpdate(user);
return "保存成功!";
}
/**
* 批量添加用户
*/
@GetMapping("/batchCreateOrUpdate")
public String batchCreateOrUpdate(){
userService.batchCreateOrUpdate();
return "保存成功";
}
/**
* 根据id删除用户
*/
@DeleteMapping("/delete/{id}")
public String delete(@PathVariable("id") Integer id){
userService.delete(id);
return "删除成功!";
}
/**
* 存储list对象
*/
@GetMapping("/saveList")
public String saveList(){
userService.saveList();
return "保存成功";
}
/**
* 读取list对象
*/
@GetMapping("/getList")
public Map<String,Object> getList(){
Map<String,Object> map = new HashMap<>();
map.put("list",userService.getList());
return map;
}
}
像 RedisConfig、RedisUtil、GsonUtil 这三个文件都是可以反复使用的,项目中有用到redis存取数据的,这三个类可以直接拿过来使用。
八、运行结果
1、(批量)新增/修改
2、根据id获取用户
3、用户列表
4、删除
可以看到,redis中已经没有key(也就是id)为8的用户了
4、存取list对象
当然,大多数情况下,应该都是redis和mysql同时使用的,可能会需要它们两个同步数据,不过这都是后话了。。。