当前位置: 首页 > news >正文

Springboot集成Redis操作缓存-06

Redis简介

Redis(Remote Dictionary Server),即远程字典服务,是一个开源的、使用ANSI C语言编写的、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

功能特点

  1. 数据结构丰富:Redis支持多种数据结构,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集等丰富的操作,且这些操作都是原子性的。
  2. 高性能:Redis将数据存储在内存中,因此其读写速度非常快。根据官方数据,Redis可以轻松支持超过10万次QPS(每秒查询率)的读写频率。
  3. 持久化:虽然Redis主要将数据存储在内存中,但它也提供了持久化的功能。Redis可以周期性地将更新的数据写入磁盘,或将修改操作写入追加的记录文件,以确保数据的持久性。
  4. 主从同步和复制:Redis支持主从同步,数据可以从主服务器向任意数量的从服务器上同步。从服务器可以是关联其他从服务器的主服务器,这使得Redis可执行单层树复制。
  5. 哨兵(Sentinel)和集群(Cluster):Sentinel可以管理多个Redis服务器,提供监控、提醒以及自动的故障转移功能。Redis Cluster则允许将数据分布在多个Redis节点上,以实现横向扩展和负载均衡。
  6. 分布式锁:Redis还可以用作分布式锁,以确保在分布式系统中对共享资源的访问是同步的。
  7. 发布/订阅机制:Redis完全实现了发布/订阅机制,允许从数据库在任何地方同步树时,订阅一个频道并接收主服务器完整的消息发布记录。

应用场景

如缓存服务、消息队列、分布式锁等。由于其高性能和丰富的功能,Redis已经成为许多主流架构中不可或缺的一部分。

关于Redis的安装和使用,可以根据不同的操作系统和需求选择相应的方法。例如,在Windows系统中,可以通过解压并双击redis-server.exe和redis-cli.exe来启动服务器和命令窗口。在Linux系统中,则可以按照详细的安装部署教程进行安装和配置。同时,Redis也提供了丰富的命令和API,以满足不同的使用需求。

Redis安装

笔者是在Macos系统下采用HomeBrew进行的安装

安装

brew install redis

启动

  • brew启动
brew services list
brew services start redis
brew services stop redis
ps -ef | grep redis
  • redis命令启动
# 启动
redis-server# 客户端工具
redis-cli# 设置密码
CONFIG SET requirepass YOUR_PASSWORD
auth YOUR_PASSWORD

springboot-redis模块

模块工程结构

在这里插入图片描述

pom.xml

依赖版本可参考 springbootSeries 模块中pom.xml文件中的版本定义

    <dependencies><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-consul-discovery</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency></dependencies>

application.properties配置

spring.profiles.active = dev
spring.application.name=springbootRedis
server.port=18087spring.cloud.consul.host=localhost
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.service-name=${spring.application.name}spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.password=

SpringbootApplication启动类

添加 @EnableDiscoveryClient 注解

@Slf4j
@SpringBootApplication(scanBasePackages = {"com.korgs",  "cn.hutool.extra.spring"})
@Configuration
@EnableConfigurationProperties
@ServletComponentScan
@RestController
@EnableDiscoveryClient
public class SpringbootRedisApplication {public static void main(String[] args) {SpringApplication.run(SpringbootRedisApplication.class, args);}@GetMapping("/helloworld")public BaseResponse helloWorld(){log.info(LogGenerator.trackLog()+ "msg="+ "I am busy to handle this request.");return BaseResponse.success("hello world");}
}

java-redis实现

Redis bean实现

在使用时有两个模板配置,Redis适用于需要持久化、复杂数据结构和高性能的场景,而Cache Manager适用于简单的缓存需求,部署和管理相对简单。具体使用哪种方案应根据实际需求和场景来决定。

@Configuration
public class RedisConfig {@BeanRedisConnectionFactory connectionFactory() {return new LettuceConnectionFactory();}@BeanRedisTemplate<String, String> redisTemplate(RedisConnectionFactory connectionFactory) {RedisTemplate<String, String> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer( new JdkSerializationRedisSerializer());return template;}@BeanStringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}
}

RedisController实现

@Slf4j
@RestController
@RequestMapping("/api/load")
public class RedisController {//Pushing an item to a List using [Reactive]RedisTemplate@Resource(name="redisTemplate")private ListOperations<String, String> listOps;//String-focused Convenience Classes@Autowiredprivate StringRedisTemplate redisTemplate;@GetMapping("/v1/listOperator")public BaseResponse<String> listOperator(String uuid, String url){log.info(LogGenerator.trackLog() + uuid + ":" + listOps.size(uuid));String cache = listOps.index(uuid, 0);if (StrUtil.isEmpty(cache)){listOps.leftPush(uuid, url);return BaseResponse.success(uuid + ":" + url);}listOps.leftPush(uuid, url);return BaseResponse.success(uuid + ":" + cache);}@GetMapping("/v1/stringOperator")public BaseResponse<String> stringOperator(String uuid, String url){String cache = redisTemplate.opsForValue().get(uuid);log.info(LogGenerator.trackLog() + uuid + ":" + cache);if (StrUtil.isEmpty(cache)){redisTemplate.opsForValue().set(uuid, url);return BaseResponse.success(uuid + ":" + url);}redisTemplate.opsForValue().set(uuid, url);return BaseResponse.success(uuid + ":" + cache);}//how to use the RedisCallback interfacepublic void useCallback() {redisTemplate.execute(new RedisCallback<Object>() {public Object doInRedis(RedisConnection connection) throws DataAccessException {Long size = connection.dbSize();// Can cast to StringRedisConnection if using a StringRedisTemplate((StringRedisConnection)connection).set("key", "value");return size;}});}
}

源码下载

涉及模块:

  • springboot-redis:18087

源码下载:

  • 基础框架源码下载
  • Springboot集成Redis操作缓存

源码运行方法:

  • 模块详细功能说明和运行测试方法
http://www.lryc.cn/news/344009.html

相关文章:

  • 【WPF】聊聊WPF中INotifyPropertyChanged [TOC]
  • SpringBoot Actuator未授权访问漏洞的解决方法
  • AI大模型探索之路-训练篇18:大语言模型预训练-微调技术之Prompt Tuning
  • Ollamallama
  • 苹果Mac用户下载VS Code(Universal、Intel Chip、Apple Silicon)哪个版本?
  • Linux(Ubuntu)安装CGAL(非root)
  • hadoop学习---基于Hive的教育平台数据仓库分析案例(三)
  • RAFT:引领 Llama 在 RAG 中发展
  • 上海亚商投顾:沪指缩量调整 合成生物概念股持续爆发
  • Maven+Junit5 + Allure +Jenkins 搭建 UI 自动化测试实战
  • docker学习笔记(三)搭建NFS服务实验
  • super关键字
  • 【经典算法】LeetCode 200. 岛屿数量(Java/C/Python3/Go实现含注释说明,中等)
  • Hive SQL-DQL-Select查询语句用法详解
  • 沙盘Sandboxie v5.56.4
  • Arcpy开发记录
  • Android使用itextpdf操作PDF文档
  • llama_index微调BGE模型
  • 什么是限流?常见的限流算法
  • ZL-0895小动物活动记录仪可同时检测8只动物的活动量
  • 注册测绘师的前世今生
  • Python中的异常处理:深入探索try-except-finally结构
  • 【R语言】边缘概率密度图
  • 中国结(科普)
  • 使用Android Studio 搭建AOSP FrameWork 源码阅读开发环境
  • 区块链 | IPFS:CID
  • PostgreSQL(十二)报错:Tried to send an out-of-range integer as a 2-byte value: 51000
  • Linux守护进程
  • HarmonyOS 应用开发——入门
  • 开源免费的发票识别OCR应用:Invoice