Springboot基于Redis的高性能分布式缓存数据库的实现与实例

一、引言

在现代的分布式系统和高并发应用中,缓存机制显得尤为重要。Redis作为一种开源(BSD许可)的内存键值存储,因其高性能、丰富的数据结构和多样化的应用场景,成为开发者们的首选。在这篇博客中,我们将详细介绍Redis的背景与概念,探讨其应用场景,并指导在Linux环境下安装Redis以及集成至Springboot项目中使用。

二、 Redis简介与概念

Redis简介

Redis(Remote Dictionary Server)是由Salvatore Sanfilippo于2009年开发的开源内存数据库。与传统的关系型数据库不同,Redis是一个内存中的数据结构存储系统,它不仅支持键-值数据,还支持丰富的数据结构如字符串(String)、哈希(Hash)、列表(List)、集合(Set)、有序集合(Sorted Set)等。

Redis的特点

  1. 高性能:Redis数据存储在内存中,读写速度极快。
  2. 多样的数据结构:支持字符串、哈希、集合、列表、有序集合等多种数据结构。
  3. 持久化:提供RDB快照和AOF两种持久化机制。
  4. 主从复制:支持数据复制,提供高可用性。
  5. 分布式特性:通过Redis Cluster实现数据的自动分片与高可用性。

三、 Redis的应用场景

缓存

Redis的高读写性能使其成为缓存解决方案的首选。将频繁访问的数据缓存起来,可以极大地提高系统的响应速度和吞吐量。如网站页面缓存、数据库查询结果缓存等。

会话存储

在分布式系统中,使用Redis存储用户会话信息可以确保跨服务器的一致性,提高系统规模化处理能力。

消息队列

Redis的列表(List)和发布/订阅(Pub/Sub)功能使其可以用来构建消息队列,高效处理异步任务。

分布式锁

利用Redis的SETNX(SET if Not eXists) 命令可以实现分布式锁,确保多个客户端之间操作的互斥性。

计数器

Redis的原子操作特性非常适合构建各种计数器,如页面浏览量、商品库存等。

四、 Linux环境下安装Redis

bash 复制代码
#更新系统包管理器
sudo apt-get update

#安装构建工具和依赖,Redis是用C语言编写的,所以我们首先需要安装编译Redis所需的工具和依赖包。

sudo apt-get install build-essential tcl

#下载Redis源码
mkdir  /usr/local/redis

cd redis

wget http://download.redis.io/releases/redis-6.2.6.tar.gz

#解压并编译

tar xzf redis-6.2.6.tar.gz
cd redis-6.2.6
make

#运行测试

make test 

#安装Redis
sudo make install

#修改配置文件,
vi ./redis.conf

#添加或修改以下配置
bind 127.0.0.1 前面加#注释或者将127.0.0.1修改为0.0.0.0 哪些IP可访问
daemonize no修改为yes 后台启动
requirepass 去掉前面的#号,修改后面内容 为登录密码
protected-mode yes 修改为 no 可远程连接


#启动Redis服务器 默认情况下,Redis服务器会在端口6379上启动。

./bin/redis-server   ../redis.conf
bash 复制代码
#启动Redis客户端,打开另一终端窗口,使用redis-cli连接到Redis服务器。

./bin/redis-cli

简单操作示例

bash 复制代码
# 设置键值
set mykey "Hello, Redis!"
# 获取键值
get mykey

五、Springboot整合Redis

1.添加核心依赖

XML 复制代码
<dependency>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-data-redis</artifactid>
</dependency>

2.Redis的yml配置设置

XML 复制代码
# 端口
server:
  port: 8008
spring:
  application:
    # 应用名称
    name: spring-boot-redis
  # redis 配置
  redis:
    host: 10.98.2.33
    #超时连接
    timeout: 1000ms
    jedis:
      pool:
        #最大连接数据库连接数,设 0 为没有限制
        max-active: 8
        #最大等待连接中的数量,设 0 为没有限制
        max-idle: 8
        #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
        max-wait: -1ms
        #最小等待连接中的数量,设 0 为没有限制
        min-idle: 0

3.编写测试用例

java 复制代码
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
@RestController
@RequestMapping("/redis")
public class RedisController {
    @Resource
    private StringRedisTemplate stringRedisTemplate ;
    @RequestMapping("/setGet")
    public String setGet (){
        stringRedisTemplate.opsForValue().set("user1","smile");
        return stringRedisTemplate.opsForValue().get("user1") ;
    }
    @Resource
    private RedisTemplate redisTemplate ;
    /**
     * 设置 Key 的有效期 10 秒
     */
    @RequestMapping("/setKeyTime")
    public String setKeyTime (){
        redisTemplate.opsForValue().set("timeKey","timeValue",10, TimeUnit.SECONDS);
        return "success" ;
    }
    @RequestMapping("/getTimeKey")
    public String getTimeKey (){
        // 这里 Key 过期后,返回的是字符串 'null'
        return String.valueOf(redisTemplate.opsForValue().get("timeKey")) ;
    }
}

4.自定义序列化配置类

java 复制代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
 * Redis 配置
 */
@Configuration
public class RedisConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisConfig.class) ;
    /**
     * 序列化配置
     */
    @Bean
    public RedisTemplate<string, serializable> redisTemplate
            (LettuceConnectionFactory  redisConnectionFactory) {
        LOGGER.info("RedisConfig == &gt;&gt; redisTemplate ");
        RedisTemplate<string, serializable> template = new RedisTemplate&lt;&gt;();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

5.序列化配置类使用测试

java 复制代码
import com.boot.redis.entity.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/User")
public class UserController {
    @Resource
    private RedisTemplate redisTemplate ;
    @RequestMapping("/setUser")
    public String setUser (){
        User user = new User() ;
        user.setName("cicada");
        user.setAge(22);
        List<string> list = new ArrayList&lt;&gt;() ;
        list.add("小学");
        list.add("初中");
        list.add("高中");
        list.add("大学");
        user.setEducation(list);
        redisTemplate.opsForValue().set("userInfo",user);
        return "success" ;
    }
    @RequestMapping("/getUser")
    public User getUser (){
        return (User)redisTemplate.opsForValue().get("userInfo") ;
    }
}

结论:

Redis作为一种高性能的内存数据库,不仅适用于缓存场景,还可以应用于会话存储、消息队列、分布式锁和计数器等多个方面。通过本文的介绍,相信您对Redis有了一个全面的了解,并能够在Linux环境中成功安装和使用Redis。在实际项目中,合理使用Redis,可以显著提高系统的性能和可靠性。

相关推荐
xujiangyan_21 小时前
Redis详解
数据库·redis·缓存
摇滚侠1 天前
Spring Boot 3零基础教程,IOC容器中组件的注册,笔记08
spring boot·笔记·后端
Y编程小白1 天前
PostgreSQL在Linux中的部署和安装教程
数据库·postgresql
程序员小凯1 天前
Spring Boot测试框架详解
java·spring boot·后端
程序员小凯1 天前
Spring Boot缓存机制详解
spring boot·后端·缓存
TiAmo zhang1 天前
SQL Server 2019实验 │ 数据库和表的创建、修改与删除
数据库·oracle
disanleya1 天前
MySQL默认密码不安全?如何首次登录并强化?
数据库·mysql·安全
花开富贵贼富贵1 天前
MySQL 核心高级特性
运维·数据库·mysql
hello 早上好1 天前
深入 Spring 依赖注入底层原理
数据库·sql·spring
API快乐传递者1 天前
抓取淘宝商品详情商品数据API接口调用说明文档|获取淘宝商品价格主图数据等
数据库