首页 > 数据库 >【转载】Springboot2.x 使用 Redis

【转载】Springboot2.x 使用 Redis

时间:2023-12-19 13:22:56浏览次数:36  
标签:缓存 demo Redis springframework Springboot2 org import 转载 com

参考

注意

  1. class java.lang.Integer cannot be cast to class com.xiaqiuchu.demo.entity.Student (java.lang.Integer is in module java.base of loader 'bootstrap'; com.xiaqiuchu.demo.entity.Student is in unnamed module of loader 'app')
    注解缓存时缓存的方法缓存值,update 返回的是数字类型,导致缓存查询的时候报错转换失败。

  2. entity 类需要 implements java.io.Serializable ,否则可能会导致缓存储存时序列化失败或错误。

环境

环境 版本 操作
windows 10
vs code 1.84.2
Spring Boot Extension Pack v0.2.1 vscode插件
Extension Pack for Java v0.25.15 vscode插件
JDK 11
Springboot 2.3.12.RELEASE
mybatis-spring-boot-starter 2.1.4 mvn依赖
spring-boot-starter-cache mvn依赖
Apache Maven 3.8.6
Redis 3.0.504 windows 版本,已停更,建议 linux 中使用

步骤

配置

  1. 添加 pom.xml 依赖。
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 在配置文件中 application.properties 增加配置。

不仅仅这些配置,还有其他配置以及连接池的配置

# redis配置
spring.redis.host=127.0.0.1
spring.redis.port=6379
# 连接池配置,连接池配置还需要添加其他依赖。 https://juejin.cn/post/7076244567569203208
  1. src\main\java\com\xiaqiuchu\demo\config 增加 RedisConfig.java
package com.xiaqiuchu.demo.config;

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

  @Bean
  public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
    RedisTemplate<String, Object> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    // key 序列化类
    template.setKeySerializer(new StringRedisSerializer());
    // value 序列化类
    template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    return template;
  }
}

使用

  1. 代码操作。
package com.xiaqiuchu.demo.service;

import java.time.Duration;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import com.xiaqiuchu.demo.entity.Student;
import com.xiaqiuchu.demo.mapper.StudentMapper;

@Service
public class StudentService {
    @Resource
    StudentMapper studentMaper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 手动管理缓存
     * @param id
     * @return
     */
    public Student findByIdFromCache(Integer id){
        String cacheKey = "StudentService" + id;
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        if(redisTemplate.hasKey(cacheKey) == null || redisTemplate.getExpire(cacheKey) < 1){
            System.out.println("==查询数据库==");
            valueOperations.set(cacheKey, studentMaper.findById(id), Duration.ofHours(2));
        }
        return (Student) valueOperations.get(cacheKey);
    }
}

  1. 注解方式

注意:注解方式是缓存的方法返回值,但是像 mybatis 中 update 操作默认返回的是更新条数,如果直接返回更新条数就会导致缓存储存为数字类型,在查询的时候报错 class java.lang.Integer cannot be cast to class com.xiaqiuchu.demo.entity.Student (java.lang.Integer is in module java.base of loader 'bootstrap'; com.xiaqiuchu.demo.entity.Student is in unnamed module of loader 'app')

注解方式获取 key 可以通过 . 方式获取对象的属性。

package com.xiaqiuchu.demo.service;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.xiaqiuchu.demo.entity.Student;
import com.xiaqiuchu.demo.mapper.StudentMapper;

@Service
public class StudentService {
    @Resource
    StudentMapper studentMaper;

    // 该注解用于标记方法的返回结果可以被缓存。当下次调用相同的方法时,如果缓存中存在相同的参数,则直接从缓存中获取结果,而不执行方法体内的代码。如果缓存中不存在相同的参数,则执行方法体内的代码,并将结果存入缓存中。
    @Cacheable(value = "StudentService", key = "#id")
    public Student findById(Integer id){
        System.out.println("==查询==");
        return studentMaper.findById(id);
    }

    public Integer insert(Student student){
        return studentMaper.insert(student);
    }

    // 该注解用于标记方法的返回结果需要放入缓存。无论缓存中是否已存在相同的参数,每次调用该方法都会执行方法体内的代码,并将结果存入缓存中。
    // 方法返回类型要一致,不然储存的就是 Integer。。。 
    @CachePut(value = "StudentService", key = "#student.id")
    public Student updateById(Student student){
        Integer updateNum = studentMaper.updateById(student);
        Assert.isTrue(updateNum > 0, "更新失败");
        return student;
    }

    // 该注解用于标记方法执行后需要清除特定的缓存项。可以指定要清除的缓存项的key,或者通过allEntries参数设置为true来清除所有缓存项。
    @CacheEvict(value = "StudentService", key = "#id")
    public Integer deleteById(Integer id){
        System.out.println("==删除==");
        return studentMaper.deleteById(id);
    }
    
}

标签:缓存,demo,Redis,springframework,Springboot2,org,import,转载,com
From: https://www.cnblogs.com/xiaqiuchu/p/17913496.html

相关文章

  • redis模糊删除
     客户端连接redis,查看数据 退出 执行exit,退出客户端 执行删除命令(利用xargs命令)redis-cli-apasswordkeys"key*"|xargsredis-cli-apassworddelpassword为密码keys"key*" 即为模糊删除的key查看结果 ......
  • Redis7 复制
    1、主从复制1.1、常用命令1、主从复制从库操作replicaof主库IP主库端口或者slaveof主库IP主库端口2、取消主从slaveofnoone1.2、主从复制原理和工作流程1、slave启动,同步初请slave启动成功连接到master后会发送一个sync命令slave首次全新连接master,一次完全同步(全......
  • redis实践经验总结
    Redis内存配置当Redis内存不足时,可能导致Key频繁被删除、响应时间变长、QPS不稳定等问题。当内存使用率达到80%以上时就需要我们警惕,并快速定位到内存占用的原因。一般来说,会有以下几种占用内存的情况:数据内存是Redis最主要的部分,存储Redis的键值信息。主要问题是BigKey问题......
  • redis中的hash tag
    在集群模式下,如果lua脚本同时操作多个key,可能会出现:CROSSSLOTKeysinrequestdon'thashtothesameslot的错误。这种情况下,可以通过{...},来指定多个key使用相同的内容进行hash,例如:user:{123}:username和user:{123}:email就会用123去hash,保证落到同一个slot,也就是可以在单个......
  • linux环境变量(转载)
    阅读目录一、Linux环境变量介绍1.1Linux环境变量介绍1.2Linux环境变量分类1.3Linux常用的环境变量二、Linux查看环境变量三、Linux添加环境变量3.1添加系统级环境变量(需root权限、针对所有用户、永久生效)3.2添加用户级环境变量3.3SSH/串口终端临时添加环境变量四、Lin......
  • Redis上层数据类型设计
    StringString即字符串对象,是Redis使用最多的数据类型,其使用key-value结构,key为唯一标识,value为存储内容。value不仅可以是字符串,也可以是数字,包括整数或者浮点数。value最多可以容纳的大小为512MB。>SETnameErickRenOK>SETage19OK>GETname"ErickRen">GETage......
  • nginx+lua+redis实现灰度发布
    前言:授人以鱼不如授人以渔.先学会用,在学原理,在学创造,可能一辈子用不到这种能力,但是不能不具备这种能力。这篇文章主要是沉淀使用nginx+lua+redis实现灰度,当我们具备了这种能力,随时可以基于这种能力和思想调整实现方案:比如nginx+lua+(其他数据源)、nginx+(其他脚本语言)一、灰度......
  • 2、SpringBoot2之入门案例
    2.1、创建Maven工程2.1.1、创建空项目2.1.2、设置项目名称和路径2.1.3、设置项目sdk2.1.4、项目初始状态注意:需要关闭项目再重新打开,才能看到SpringBoot-Part文件夹2.1.5、配置maven2.1.6、创建module右击SpringBoot-Part文件夹,创建新module选择maven配......
  • redis系列--redis单机
    Redis是单线程吗?Redis的单线程主要是指Redis的网络IO和键值对读写都是由一个线程来完成的,这也是Redis对外提供键值存储服务的主要流程。但redis的其他功能,比如持久化,异步删除,集群数据同步等,其实是由额外的线程执行的。Redis单线程为什么还能这么快?因为它所有的数据都在内存中,所......
  • Docker Compose 快速搭建 Redis 单机版
    Redis是非常流行的缓存中间件,其具有功能强大和部署简单的优势,我们在CentOS上使用yum就能够在线安装Redis。之所以要介绍使用Docker进行容器化部署Redis,主要原因是当前容器化部署是主流,而且能够保障服务器文件系统的整洁。本篇博客主要介绍如何使用docker-compose快速......