springboot使用redis

springboot使用redis

redis-service.exe : 服务端,启动后不要关闭

redis-cli.exe : 客户端,访问redis中的数据

redisclient-win32.x86_64.2.0.jar : redis的图形界面客户端,执行方式是在这个文件的目录执行

复制代码
java -jar redisclient-win32.x86_64.2.0.jar

或者在这个jar包的目录下点击即可直接执行

点击server,点击add,设置端口号就可以访问redis了

springboot使用redis步骤

  1. 添加依赖

    redis起步依赖,导入后可以直接使用RedisTemplate

    RedisTemplate实际上使用的是lettuce客户端库

    复制代码
    	<dependency>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-data-redis</artifactId>
    	</dependency>
  2. 在application.properties中配置redis连接

    #指定redis信息 (如 host, ip, password)

    spring.redis.host=localhost

    spring.redis.port=6379

    #没有密码可以不用配置这个

    #spring.redis.password=123456

  3. 使用redisTemplate来访问redis服务器

    import org.springframework.data.redis.core.RedisTemplate;

    import org.springframework.data.redis.core.StringRedisTemplate;

    import org.springframework.data.redis.core.ValueOperations;

    import org.springframework.web.bind.annotation.GetMapping;

    import org.springframework.web.bind.annotation.PathVariable;

    import org.springframework.web.bind.annotation.PostMapping;

    import org.springframework.web.bind.annotation.RestController;

    import javax.annotation.Resource;

    @RestController

    public class RedisController {

    复制代码
    /**
     * 需要注入redis模板
     *
     * 对于RedisTemplate的泛型情况,
     * 可以使用<String, String>
     *       <Object, Object>
     *       或者不写泛型
     *
     *  注意,属性的名称必须为redisTemplate,因为按名称注入,框架创建的对象就是这个名字的
     */
    @Resource
    private RedisTemplate redisTemplate;
    
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    
    // 添加数据到redis
    @PostMapping("/redis/addstring")
    public String addToRedis(String name, String value) {
    
        // 操作Redis中的string类型的数据,先获取ValueOperation
        ValueOperations valueOperations = redisTemplate.opsForValue();
    
        // 添加数据到redis
        valueOperations.set(name, value);
        return "向redis添加string类型的数据";
    }
    
    // 从redis获取数据
    @GetMapping("/redis/getk")
    public String getData(String key) {
    
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object v = valueOperations.get(key);
        return "key是" + key + ",它的值是:" + v;
    }
    
    @PostMapping("/redis/{k}/{v}")
    public String addStringKV(@PathVariable String k,
                              @PathVariable String v) {
    
        // 使用StringRedisTemplate对象
        stringRedisTemplate.opsForValue().set(k,v);
        return "使用StringRedisTemplate对象添加";
    }
    
    @GetMapping("/redis/{k}")
    public String getStringValue(@PathVariable String k) {
    
        // 获取String类型的value
        String v = stringRedisTemplate.opsForValue().get(k);
        return "从redis中通过" + k + "获取到string类型的v=" + v;
    }

    }

redisTemplate对象有好几种,上面代码中给了两种

一种为RedisTemplate,这种是有泛型的,泛型类型为<String, String> 或者 <Object, Object> 或者不添加泛型,当用它来向redis服务器中存入String类型的数据时,会出现乱码

使用postman

明明存入成功了,在redis中查询的时候是带有乱码前缀的

直接通过"lisi"它的值是可以取出的

可见在RedisTemplate在存取中做了手脚.

当我们使用StringRedisTemplate对象存取String类型的数据时,是没有乱码的



redis服务器中的数据

数据正常展示

StringRedisTemplate和RedisTemplate

上面说到了这两者在存取中的差异

  • StringRedisTemplate : 这个类将key和value都做String处理,使用的是String的序列化,可读性好
  • RedisTemplate : 把key和value经过了序列化,key和value都是序列化的内容,不能直接识别,默认使用的是JDK的序列化,可以修改为其他的序列化

序列化作用 :

序列化是将对象转换为可传输字节序列的过程,反序列化是将字节序列还原为原对象的过程.序列化最终的目的是为了对象可以跨平台存储和进行网络的传输

序列化的方式 :

序列化只是一种拆装对象的规则,那么这种规则也就多种多样,常见的有JDK(不支持跨语言),json,xml,Hessian等

我们上面的RedisTemplate类的存储就是JDK方式的

jdk方式的序列化

java的序列化 : 把java对象转换为byte[],二进制数据
json序列化 : json序列化功能将对象转换为json格式或者将其转换回对象,如Student对象转换为{"name":"张三","age":"20"}

序列化的方式可以改变

复制代码
    /** 设置RedisTemplate序列化机制
     *  可以设置 key 的序列化,也可以设置 value 的序列化
     *  也可以同时设置
     */
    @PostMapping("/redis/addstr")
    public String addString(String k, String v) {

        // 设置RedisTemplate的序列化机制
        // 设置key为string类型的序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置value的序列化
        redisTemplate.setValueSerializer(new StringRedisSerializer());

        redisTemplate.opsForValue().set(k, v);
        return "添加了k和v";
    }

使用json方式的序列化

  1. 创建实体类,需要实现序列化接口,最好有序列化的UID

    import java.io.Serializable;

    public class Student implements Serializable {

    复制代码
    private static final long serialVersionUID = -7839813688155519106L;
    private Integer id;
    private String name;
    private Integer age;
    
    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 Integer getAge() {
        return age;
    }
    
    public void setAge(Integer age) {
        this.age = age;
    }

    }

idea生成序列化UID的方式,需要先在setting中开启,如下

然后将光标放在类名上,alt+enter

  1. 在方法中设置序列化方式

    复制代码
    /**
     * 使用json序列化
     */
    @PostMapping("/redis/addjson")
    public String addJson() {
    
        Student student = new Student();
        student.setName("zhangsan");
        student.setAge(20);
        student.setId(1);
    
        // 设置key为string的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置value为json的序列化方式,json为Student类型的方式组织,所以需要传入Student.class
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
        redisTemplate.opsForValue().set("myStudent", student);
        return "存入json类型的数据student";
    }
  2. 测试访问url

  3. 在redis服务端检查数据

果然,数据的value已经以json的方式存入内存中了.

  1. 使用json的方式反序列化将数据取出

    /**

    * 使用json序列化

    */

    @PostMapping("/redis/addjson")

    public String addJson() {

    复制代码
        Student student = new Student();
        student.setName("zhangsan");
        student.setAge(20);
        student.setId(1);
    
        // 设置key为string的序列化方式
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        // 设置value为json的序列化方式,json为Student类型的方式组织,所以需要传入Student.class
        redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Student.class));
        redisTemplate.opsForValue().set("myStudent", student);
        return "存入json类型的数据student";
    }


反序列化的时候必须得指定序列化的方式,要不然不能取出数据

相关推荐
Coder-coco1 小时前
点餐|智能点餐系统|基于java+ Springboot的动端的点餐系统小程序(源码+数据库+文档)
java·vue.js·spring boot·小程序·论文·毕设·电子点餐系统
嘟嘟w1 小时前
Spring 核心注解深度分析
java·后端·spring
程序员小单1 小时前
WebSocket 与 Spring Boot 整合实践
spring boot·websocket·网络协议
武子康1 小时前
大数据-160 Apache Kylin Cube 实战:从建模到构建与查询(含踩坑与优化)
大数据·后端·apache kylin
ComplexPy2 小时前
ZKMall-B2B2C Redission延时队列
java·redis
q***96582 小时前
深入解析Spring Boot中的@ConfigurationProperties注解
java·spring boot·后端
发现你走远了2 小时前
2025 idea 指定配置环境运行springboot 设置active和env启动端口,多端口启动 (保姆级图文)
java·spring boot·intellij-idea
Jamesvalley3 小时前
flask处理所有logging
后端·python·flask
databook3 小时前
别急着转投 Polars!Pandas 3.0 带着“黑科技”杀回来了
后端·python·数据分析