Spring Boot整合Redis,实现缓存功能

前言

Redis 属于开源、键值对型的数据存储系统。支持网络、可基于内存、可持久化的日志型数据库。它可用作数据库、缓存、消息中间件。

Redis 通常用来缓存一些经常被访问的热点数据,亦或者需要耗费大量资源的内容。通过把这些内容放到 Redis 中,可以让应用程序快速地读取它们,并能够提升网站的访问速度,大大降低数据库的压力。

正文

在进入今天的内容分享之前,进修者会让大家了解到 Redis 优缺点、常见适用场景及其它相关概念。

Redis优缺点

Redis优点

Redis优点有很多,其中最大的优点就是开源,其优点不仅于此!

  • 具有原子性,即:Redis 的所有单个命令的操作都是原子性的;
  • 具有丰富的数据类型,它支持字符串、哈希、列表、集合、有序集合等;
  • 具有丰富的特性,支持 Publish/Subscribe 等特性;
  • 支持机器重启后,重新加载数据的模式,不会丢失数据;
  • 支持主从模式复制,支持分布式;
  • 支持高并发,官宣:支持 10 万级别的并发读写;
  • 完全基于内存,数据实时读写内存,定时闪回到文件中,性能极高,读写速度快,Redis 能支持超过 100Kb/s 的读写速度。

Redis 是高性能缓存数据库,它完全基于内存,数据结构简单,采用单线程,使用多路 I/O 复用模型(非阻塞 IO),另外 Redis 构建了自己的 VM 机制,没有使用 OS 的 Swap,而是自己实现。通过 VM 功能可以实现冷热数据分离,可避免因内存不足而造成访问速度下降的问题。

Redis 缺点

大家都知道计算机的内存是非常珍贵的资源,这必然会带来一些缺陷;因此其主要局限在较小数据量的高性能操作和运算上。即:数据库容量受到物理内存的限制,不能实现海量数据的高性能读写。

  • Redis 不支持复杂逻辑查询,不适合大型项目的要求;
  • 相比于关系型数据库,其存储结构相对简单,因此 Redis 并不能对复杂的逻辑关系提供很好的支持;
  • 没有原生的可扩展机制,不具备自身可扩展能力,需要依赖客户端来实现分布式读写;
  • Redis 使用的最佳方式是全部数据 In-Memory,虽然 Redis 也提供持久化功能,但实际更多的是一个 disk-backed 功能,和传统意义上的持久化区别比较明显。

Redis常见适用场景

Redis 应用非常广泛,可以用作缓存、分布式、消息队列、计数器和排行榜等场景。

缓存:目前来说是中大型网站都会使用的提升手段,合理的利用缓存能够提升网站的访问速度,大大降低数据库的压力;
分布式 Session 共享:集群模式下,基于 Redis 实现 session 共享;
分布式锁:在维护库存、“秒杀” 购物等一些场合,为保证并发访问时操作的原子性,可利用 Redis 实现分布式锁来完成这些功能;
消息队列:Redis 提供发布/订阅及阻塞队列功能,能实现一个简单的功能较弱消息队列系统。譬如:在一些功能简单的应用系统里可以推荐使用;
计数器:应用在电商网站的浏览量、视频点击量等方面。针对这种场合比较适合使用 Redis 提供的 incr 命令来实现计数器功能,另外它具有原子性单线程操作,保证了统计不会出错,本身又是内存操作,速度非常快。
排行榜:借助 Redis 提供的有序集合能实现排行榜功能
位操作:用于海量数据(数据量上千万甚至上亿)的场景下,如:上亿用户的活跃度统计等。位操作使用 setbit、getbit、bitcount 等命令;
最新列表:Redis 列表结构,lpush 可在列表头部插入一个内容 id 作为关键字,ltrim 可用来限制列表的数量,这样列表永远为 n 个 id,无须查询最新列表,直接根据id去到对应的内容页即可。

内存优化建议

  1. 尽可能使用哈希表(Hash 数据结构),因为 Redis 在储存小于100个字段的 Hash 结构上,其存储效率非常高,因此在不需要使用集合 set 或 list 操作的情况下,尽可能使用 hash 结构。
  2. 合理使用 Redis 提供的内存回收策略,比如:过期数据清除、expire 设置数据过期时间等;
  3. 充分利用共享对象池:Redis 在启动时会自动创建 0-9999 的整数对象池,对于 0-999 的内部整数类型的元素、整数值对象都会直接引用整数对象池中的对象,因此尽量使用 0-9999 整数对象可节省内存;
  4. 另外根据业务场景,考虑使用 BITMAP。

创建 Maven 项目

使用 idea 开发工具,创建 Maven 工程。创建 Spring Boot 这里不做多说,想必大家应该都会!如果不熟悉的,可以参考这篇文章。

搭建环境:新手小白入门Spring Boot,搞懂这些基本配置,可以少走很多弯路

配置 pom 依赖

创建项目的时候,可以通过勾选相关依赖进行初始化加载依赖包配置;当然你也可以参考下面的基本依赖包配置(直接拷贝到自己的工程 pom.xml 中即可)。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.15.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.erbin</groupId>
    <artifactId>springbootdemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springbootdemo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>8.0.27</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.20</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>io.projectreactor</groupId>
            <artifactId>reactor-test</artifactId>
            <scope>test</scope>
        </dependency>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

配置数据库连接池

创建 application.properties 文件,配置数据库连接池等通用配置。具体配置如下:

spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&useTimezone=true
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# mybatis configuration
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.erbin.springbootdemo.bean
mybatis.configuration.log-impl=org.apache.ibatis.logging.slf4j.Slf4jImpl
# slf4 log level
logging.level.com.erbin.springbootdemo=info
# redis config, the default password is empty!
sring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
#spring.redis.password=root
#连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=100
# 连接池中的最小空闲连接
spring.redis.jedis.pool.max-idle=10
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=100000
# 连接超时时间(毫秒)
spring.redis.timeout=5000
#默认是索引为0的数据库
spring.redis.database=0

编写项目代码

定义配置类

自定义配置类,指定key、value以及field的序列化方式。这样后面使用时不需要每次都指定,非常的方便。

package com.erbin.springbootdemo.config;

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.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.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

/**
 * redis config
 *
 * @author trainer
 * @date 2023/6/24
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();

        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setConnectionFactory(factory);
        // key序列化方式
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        template.setKeySerializer(redisSerializer);
        // value序列化
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // value hashMap 序列化  filed value
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.setHashKeySerializer(redisSerializer);
        return template;
    }

    /**
     * springboot内置的注解配置方法
     * @param factory
     * @return
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        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);
        // 配置序列化(解决乱码的问题),过期时间1800秒
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(1800)) //缓存过期30分钟
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))//设置key的序列化方式
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) //设置value的序列化
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
                .cacheDefaults(config)
                .build();
        return cacheManager;
    }

}

实体类

以用户实体类为例,具体代码如下:

package com.erbin.springbootdemo.bean;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

import java.io.Serializable;

/**
 * 用户实体类
 * @author trainer
 * @date 2023/6/3
 */
@Data
@ToString
public class User implements Serializable {
    @Getter
    @Setter
    private String userId;

    @Getter
    @Setter
    private String userName;

    @Getter
    @Setter
    private String userPass;

    @Getter
    @Setter
    private String telphone;

}

Mapper接口

UserMapper 类对数据操作的 Mapper 接口层,主要包括针对用户的增改查,删除操作这里不做说明(一般为逻辑删除)。实例代码如下:

package com.erbin.springbootdemo.mapper;

import com.erbin.springbootdemo.bean.User;
import org.apache.ibatis.annotations.*;

/**
 * 数据存储层实现类
 * @author trainer
 * @date 2023/6/3
 */
@Mapper
public interface UserMapper {

    @Select("select * from t_user where user_name = #{name}")
    User queryUserByName(@Param("name") String name);

    @Insert("insert into t_user (user_id, user_name, user_pass, telphone) values(#{userId}, #{userName}, #{userPass}, #{telphone})")
    int saveUser (User user);

    @Update("update t_user set user_name=#{userName}, user_pass=#{userPass}, telphone=#{telphone} where user_id=#{userId}")
    int updateUser (User user);
}

Service层

UserService 业务层实现类,主要处理用户增改查业务逻辑,具体实例代码如下所示:

package com.erbin.springbootdemo.service;

import com.erbin.springbootdemo.bean.User;
import com.erbin.springbootdemo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 用户业务实现类
 * @author trainer
 * @date 2023/6/3
 */
@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 手动进行缓存,需要进行注入;使用内置注解添加缓存,则不需要
     */
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * via the name of user, to query the user information
     * 先查询缓存,缓存中存在则取出;没有存入缓存并取出。
     * 使用查询注解:cacheNames表示缓存的名称 key 唯一标识;该注解的名字为 cacheNames::key---->user::1
     * 先从缓存中查看key为cacheNames::key 是否存在,如果存在则不会执行下面的方法体,
     * 如果不存在则执行方法体并把方法的返回值存入到缓存中
     * @param userName
     * @return
     */
    @Cacheable(cacheNames = {"user"}, key = "#userName")
    public User queryUserByName(String userName) {
        /*ValueOperations valueOperations = redisTemplate.opsForValue();
        // 查询缓存
        Object object = valueOperations.get("user::"+userName);
        if (!ObjectUtils.isEmpty(object)) {
            return (User) object;
        }*/
        // 存储中获取
        User user = userMapper.queryUserByName(userName);
        /*if (!ObjectUtils.isEmpty(object)) {
            // 已设置默认半个小时,也可以指定时间
            valueOperations.set("user::"+userName, user, 30, TimeUnit.MINUTES);
            return user;
        }*/
        return user;
    }

    /**
     * insert user data into t_user table
     * @param user
     * @return
     */
    public int saveUser (User user) {
        return userMapper.saveUser(user);
    }

    /**
     * update the user information via the new one
     * 修改对应的注解会确保方法被执行,同时方法的返回值也被记录到缓存中,实现缓存与数据库的同步更新
     * @param user
     * @return
     */
    @CachePut(cacheNames = {"user"}, key="user.userName")
    public int updateUser (User user) {
        return userMapper.updateUser(user);
    }
}

Controller层

UserController 控制类,提供 Restful 请求,用户可以通过发送请求来实现相应的需求。示例代码如下:

package com.erbin.springbootdemo.controller;

import com.erbin.springbootdemo.bean.User;
import com.erbin.springbootdemo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 用户请求控制器类
 * @author trainer
 * @date 2023/6/3
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * URL  根据用户名获取用户信息,要求用户名唯一不重复
     * @param userName
     * @return
     */
    @GetMapping("/queryUser")
    @ResponseBody
    public User queryUserByName(@RequestParam("userName") String userName) {
        return userService.queryUserByName(userName);
    }

    /**
     * insert the user data info the table
     * @param user
     * @return
     */
    @PostMapping("save")
    public int saveUser (@RequestBody User user) {
        return userService.saveUser(user);
    }

    /**
     * update the user data by the new user
     * @param user
     * @return
     */
    @PutMapping("update")
    public int updateUser (@RequestBody User user) {
        return userService.updateUser(user);
    }
}

开启缓存注解

在 Spring Boot 启动入口类中开启缓存注解,才可以使用缓存功能。开启方式如下所示:

package com.erbin.springbootdemo;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@MapperScan(basePackages="com.erbin.springbootdemo.mapper")
@EnableCaching  // 开启redis缓存
public class SpringbootdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootdemoApplication.class, args);
    }
}

项目测试

登入数据库,查看 t_user 表中的记录,如下图所示:

在这里插入图片描述

在浏览器通过 get 请求的方式,获取数据库中的数据,如图示:

在这里插入图片描述

查看 redis 数据库中,是否成功入库,出现下图所示信息代表缓存成功!

在这里插入图片描述

小结

目前来说,Redis 缓存是中大型网站都会使用的提升手段,合理的利用缓存能够提升网站的访问速度,大大降低数据库的压力。通过上面内容的学习,我相信大家应该学会 Spring Boot 如何整合 Redis,实现缓存功能了。那么该内容分享到此结束,咱们下期不见不散!

温情提示:学习不是一蹴而就的,望大家不忘初心,继续前行!

感谢您读完了进修者的内容分享,欢迎留言区一起聊聊天,聊聊关于您对 “Spring Boot 整合 Redis,实现缓存功能” 有什么更好的想法,都可以随时叨扰!

我是进修者,期待与您肩并肩,一起进化成长!
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进修者之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值