redis进阶,springboot框架整合redis

2 篇文章 0 订阅


redis基础教程博客可以直接点链接:
https://blog.csdn.net/weixin_43876121/article/details/107685817

本篇博客源码都可以在下述github中下载获取:
https://github.com/zz1044063894/springboot-redis

整合基础配置

1.在pom文件中引入依赖

	 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

2.在yml或者properties文件中添加reids配置

笔者的redis是安装在本机的,所以直接使用localhost

//yml文件中
spring:
	redis:
		host: localhost
//properties文件中
spring.redis.host=localhost

StringRedisTemplate RedisTemplate操作redis

StringRedisTemplate基础操作

外文官网https://redis.io/
中文官网http://www.redis.cn/
点击官网上命令既可看到可用的操作

//StringRedisTemplate 的方法
stringRedisTemplate.opsForValue([string (字符串) ]
stringRedisTemplate.opsForlist()[list (列表) ]
stringRedisTemplate.opsForSet([Set (集合) ]
stringRedisTemplate.opsForHash()[Hash (散列) ]
stringRedisTemplate.opsForZSet()[ZSet (有序集合) ]
stringRedisTemplate.opsForValue([string (字符串) ]


//redistemplate方法
redisTemplate.opsForValue([string (字符串) ]
redistemplate.opsForlist()[list (列表) ]
redistemplate.opsForSet([Set (集合) ]
redistemplate.opsForHash()[Hash (散列) ]
redistemplate.opsForZSet()[ZSet (有序集合) ]

上述方法对应着各个类型的命令,凡是官方文档里拥有的命令应该都可以找到。大家可以自己尝试,在这里就一一不给出具体例子了。样例请看如下代码

@Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/redis/oprate")
    @ResponseBody
    public void text1(){
        stringRedisTemplate.opsForValue().append("msg","hello");

        //读取数据
        String msg = stringRedisTemplate.opsForValue().get("msg");
        System.out.println(msg);
        //list存储数据 
        stringRedisTemplate.opsForList().leftPush("mylist","1");
        stringRedisTemplate.opsForList().leftPush("mylist","2");
        stringRedisTemplate.opsForList().leftPush("mylist","3");
        String mylist = stringRedisTemplate.opsForList().leftPop("mylist"); //删除并查询最顶层的list数据
        System.out.println(mylist);

    }

RedisTemplate 存储对象

首先我在数据库中创建下面这张表,并写了getById方法获取对象。
在这里插入图片描述
然后,我在java创建了一个可序列化的User对象,对了上述获取对象返回值就是User对象,如果没有对对象进行序列化操作是无法将对象存在redis中的。

package com.jingchu.springboot.redis.entity;

import java.io.Serializable;

/**
 * @description: User实体类
 * @author: JingChu
 * @createtime :2020-07-31 10:12:35
 **/

public class User implements Serializable {
    private int id;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    private String name;
    private int age;
}

我们现在测试执行存储对象进redis

	/**
     * 测试保存对象
     */
    @GetMapping("/redis/save/user")
    public void test2() {
        User user = userService.getUserById(1);
        System.out.println(user);
        redisTemplate.opsForValue().set("user-01", user);
    }

结果:控制台输出
User{id=1, name=‘张三’, age=18}
redis:中出现了这样的数据在这里插入图片描述
我们在实际操作中希望存储的数据是JSON数据,而不是一些序列化值。
要实现保存JSON数据有两种方法

  • 1.将对象转换为JSON字符串存储
  • 2.自定义redisTemplate序列化对象
    第一种方式很简单,有很多共有的api供大家转换。相信大家都可以写出来。

下面我们来实现第二种:
首先创建一个config工具类,用来实现我们自定义的序列化

package com.jingchu.springboot.redis.config;

import com.jingchu.springboot.redis.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
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;


/**
 * @description: redisConfig 将对象序列化
 * @author: JingChu
 * @createtime :2020-07-31 11:19:16
 **/
@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate<Object, User> userRedisTemplate(
    			RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<Object, User > template = new RedisTemplate<Object, User> ();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<User> ser = new Jackson2JsonRedisSerializer<User>(User.class);
        template.setDefaultSerializer(ser);
        return template;
    }
}

然后在controller使用的时候直接使用使用我们自定义的序列化类
如下代码:

	@Autowired
    private RedisTemplate<Object,User> userRedisTemplate;
     /**
     * 测试保存对象
     */
    @GetMapping("/redis/save/user")
    public void test2() {
        User user = userService.getUserById(1);
        System.out.println(user);
        //默认保存对象需要使用jdk序列化然后保存到redis中
        redisTemplate.opsForValue().set("user-01", user);

        //要保存json数据进redis有两种做法
        //1。自己将对象转换为JSON字符串
        //2.自定义个redisTemplate序列化规则
        userRedisTemplate.opsForValue().set("user-01", user);
    }

当我们运行这段代码,就会发现redis中多了这样一条数据在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值