千家信息网

Spring boot集成Redis(1)—进行增加,更新,查询,批量删除等操作

发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,前言:最近工作中使用到了redis缓存,故分享一点自己总结的东西,这篇文章使用的是StringRedisTemplate进行学习,这里值的说的是,(1)StringRedisTemplate在进行批量
千家信息网最后更新 2025年02月01日Spring boot集成Redis(1)—进行增加,更新,查询,批量删除等操作

前言:最近工作中使用到了redis缓存,故分享一点自己总结的东西,这篇文章使用的是StringRedisTemplate进行学习,这里值的说的是,(1)StringRedisTemplate在进行批量删除操作时我们需对template进行序列化,(2)更新操作与添加操作一样,接下来上代码:
1.建立Spring boot项目,引入Redis依赖(pom.xml如下):

    4.0.0    com.test    redis    0.0.1-SNAPSHOT    jar    redis    Demo project for Spring Boot            org.springframework.boot        spring-boot-starter-parent        2.1.0.RELEASE                         UTF-8        UTF-8        1.8                            org.springframework.boot            spring-boot-starter-data-redis                            org.springframework.boot            spring-boot-starter-web                            org.springframework.boot            spring-boot-starter-test                                                    org.springframework.boot                spring-boot-maven-plugin                        

2.编写spring boot配置文件,这里我配置的内容简单,如需要其他的配置可以进官网去查

#Redis spring.redis.host=主机地址spring.redis.password=adminspring.redis.port=6379server.port=8081

3.接下里我们开始写测试
(1)建立实体类:
User:

package com.test.redis.entity;public class User {    private Integer id;    private String name;    private String password;    public User() {        super();    }    public User(Integer id, String name, String password) {        super();        this.id = id;        this.name = name;        this.password = password;    }    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPassword() {        return password;    }    public void setPassword(String password) {        this.password = password;    }    @Override    public String toString() {        return "User [id=" + id + ", name=" + name + ", password=" + password + "]";    }}

(2)service层,主要对redis的各种操作方法进行定义
RedisService:

package com.test.redis.service;import java.util.List;import java.util.Map;import javax.annotation.Resource;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.StringRedisTemplate;import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;import org.springframework.stereotype.Service;@Servicepublic class RedisService {    @Resource    private StringRedisTemplate template;    /**     * 存储数据或修改数据     *      * @param modelMap     * @param mapName     */    public void setKey(String mapName, Map modelMap) {        HashOperations hps = template.opsForHash();        hps.putAll(mapName, modelMap);    }    /**     * 获取数据Map     *      * @param mapName     * @return     */    public Map getMapValue(String mapName) {        HashOperations hps = this.template.opsForHash();        return hps.entries(mapName);    }    /**     * 获取数据value     *      * @param mapName     * @param hashKey     * @return     */    public Object getValue(String mapName, String hashKey) {        HashOperations hps = this.template.opsForHash();        return hps.get(mapName, hashKey);    }    /**     * 批量删除缓存数据     *      * @param keys     */    public void deleteData(List keys) {        // 执行批量删除操作时先序列化template        template.setKeySerializer(new JdkSerializationRedisSerializer());        template.delete(keys);    }}

(3)controller层代码,演示操作(添加与获取值):

package com.test.redis.web;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.test.redis.entity.User;import com.test.redis.service.RedisService;@Controllerpublic class UserController {    private static final String mapName="mapName";    @Autowired    private RedisService redisService;    @GetMapping( "/add.do")    @ResponseBody    public Map addUser(HttpServletRequest request){        Map modelMap=new HashMap();        User user=new User();        user.setName("hehename");        user.setPassword("hehePassword");        //存放hash值        modelMap.put("name", user.getName());        modelMap.put("password", user.getPassword());        redisService.setKey(mapName, modelMap);        //获取map集合        Map modelMap1= redisService.getMapValue(mapName);        Object value= redisService.getValue(mapName, "name");        System.out.println(" value : "+value);        modelMap1.put("从缓存中根据key取到的value", value);        return modelMap1;    }}

前台展示结果:

(4)删除以及获取值操作:

@GetMapping( "/delete.do")    @ResponseBody    public Map deleteUser(HttpServletRequest request){        //获取即将删除的key值,这里我们做的批量删除        List keys=new ArrayList<>();        keys.add("heheanme");        //开始执行删除操作        redisService.deleteData(keys);        //获取map集合        Map modelMap1= redisService.getMapValue(mapName);        Object value= redisService.getValue(mapName, "name");        System.out.println(" value : "+value);        modelMap1.put("从缓存中根据key取到的value", value);        return modelMap1;    }

前台显示结果:

由此可见,操作成功

0