SpringBoot依赖之Spring Data Redis的功能抽离公共服务

2024-08-27 05:28

本文主要是介绍SpringBoot依赖之Spring Data Redis的功能抽离公共服务,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

前几期我们针对在SpringBoot中的 Spring Data Redis 依赖对Redis不同类型的存储格式进行了细分学习,今天在这里进行汇总,当然如果你的项目使用的是Spring Data Redis这个原生官方以来,下面的汇总类RedisService 也可以作为公共类用在你们的项目当中。

往期文章

SpringBoot依赖之Spring Data Redis 一 String类型

SpringBoot依赖之Spring Data Redis 一 List 类型

SpringBoot依赖之Spring Data Redis 一 Hash类型

SpringBoot依赖之Spring Data Redis一集合Set

SpringBoot依赖之Spring Data Redis一有序集合Sorted Set

SpringBoot依赖之Spring Data Redis实现位图Bitmap

SpringBoot依赖之Spring Data Redis 实现地理坐标(Geospatial)

我们可以在 RedisServiceRedisController 中实现对 Redis 其他几种类型(String、List、Set、Sorted Set、Bitmap、HyperLogLog 等)的操作。以下是所有 Redis 数据类型的实现。

1. 更新 Redis 服务类

RedisService 类中添加所有类型的操作方法。

package com.dependencies.springdataredis;import org.springframework.data.domain.Range;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.Map;
import java.util.Set;/*** @author zhizhou   2024/8/17 12:01*/
@Service
public class RedisService {private final RedisTemplate<String, Object> redisTemplate;private final HashOperations<String, String, Object> hashOperations;private final ListOperations<String, Object> listOperations;private final ValueOperations<String, Object> valueOperations;private final SetOperations<String, Object> setOperations;private final ZSetOperations<String, Object> zSetOperations;private final HyperLogLogOperations<String, Object> hyperLogLogOperations;private final GeoOperations<String, Object> geoOperations;public RedisService(RedisTemplate<String, Object> redisTemplate) {this.redisTemplate = redisTemplate;this.valueOperations = redisTemplate.opsForValue();this.hashOperations = redisTemplate.opsForHash();this.listOperations = redisTemplate.opsForList();this.setOperations = redisTemplate.opsForSet();this.zSetOperations = redisTemplate.opsForZSet();this.hyperLogLogOperations = redisTemplate.opsForHyperLogLog();this.geoOperations = redisTemplate.opsForGeo();}public void saveValue(String key, String value) {redisTemplate.opsForValue().set(key, value);}public String getValue(String key) {return (String) redisTemplate.opsForValue().get(key);}//hash// 保存哈希数据public void saveToHash(String key, String field, String value) {hashOperations.put(key, field, value);}// 从哈希中获取数据public String getFromHash(String key, String field) {return (String) hashOperations.get(key, field);}// 删除哈希中的某个字段public void deleteFromHash(String key, String field) {hashOperations.delete(key, field);}// 获取哈希中的所有键值对public Map<String, Object> getAllFromHash(String key) {return hashOperations.entries(key);}//list// 向列表左侧推入值public void pushToListLeft(String key, String value) {listOperations.leftPush(key, value);}// 向列表右侧推入值public void pushToListRight(String key, String value) {listOperations.rightPush(key, value);}// 从列表左侧弹出值public String popFromListLeft(String key) {return (String) listOperations.leftPop(key);}// 从列表右侧弹出值public String popFromListRight(String key) {return (String) listOperations.rightPop(key);}// 获取列表中所有值public List<Object> getList(String key) {return listOperations.range(key, 0, -1);}//Set// Set操作public void addToSet(String key, String value) {setOperations.add(key, value);}public Set<Object> getSetMembers(String key) {return setOperations.members(key);}public boolean isMemberOfSet(String key, String value) {return setOperations.isMember(key, value);}public void removeFromSet(String key, String value) {setOperations.remove(key, value);}// Sorted Set操作public void addToSortedSet(String key, String value, double score) {zSetOperations.add(key, value, score);}public Set<Object> getSortedSetRange(String key, long start, long end) {return zSetOperations.range(key, start, end);}public void removeFromSortedSet(String key, String value) {zSetOperations.remove(key, value);}// HyperLogLog操作public void addToHyperLogLog(String key, String value) {hyperLogLogOperations.add(key, value);}public long countInHyperLogLog(String key) {return hyperLogLogOperations.size(key);}// Bitmap操作public void setBit(String key, long offset, boolean value) {valueOperations.setBit(key, offset, value);}public boolean getBit(String key, long offset) {return valueOperations.getBit(key, offset);}private static final String GEO_KEY = "locations";// 添加地理坐标public void addLocation(String member, double longitude, double latitude) {geoOperations.add(GEO_KEY, new Point(longitude, latitude), member);}// 根据坐标查询附近的地点public List<GeoResult<RedisGeoCommands.GeoLocation<Object>>> getNearbyLocations(double longitude, double latitude, double radius) {Circle within = new Circle(new Point(longitude, latitude), new Distance(radius, RedisGeoCommands.DistanceUnit.KILOMETERS));return geoOperations.radius(GEO_KEY, within).getContent();}// 获取两地之间的距离public Distance getDistance(String member1, String member2) {return geoOperations.distance(GEO_KEY, member1, member2, RedisGeoCommands.DistanceUnit.METERS);}}

2. 更新控制器类

RedisController 中添加处理这些数据类型操作的端点。

package com.dependencies.springdataredis;import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import java.util.List;
import java.util.Map;
import java.util.Set;/*** @author zhizhou   2024/8/17 12:02*/
@RestController
public class RedisController {private final RedisService redisService;public RedisController(RedisService redisService) {this.redisService = redisService;}@GetMapping("/set")public String setKey(@RequestParam String key, @RequestParam String value) {redisService.saveValue(key, value);return "保存成功";}@GetMapping("/get")public String getKey(@RequestParam String key) {return redisService.getValue(key);}@GetMapping("/hash/set")public String setHash(@RequestParam String key, @RequestParam String field, @RequestParam String value) {redisService.saveToHash(key, field, value);return "哈希值保存成功";}// 获取哈希中的数据@GetMapping("/hash/get")public String getHash(@RequestParam String key, @RequestParam String field) {return redisService.getFromHash(key, field);}// 删除哈希中的某个字段@GetMapping("/hash/delete")public String deleteHashField(@RequestParam String key, @RequestParam String field) {redisService.deleteFromHash(key, field);return "哈希字段已删除";}// 获取哈希中的所有字段和值@GetMapping("/hash/getall")public Map<String, Object> getAllHash(@RequestParam String key) {return redisService.getAllFromHash(key);}// 向列表左侧推入值@GetMapping("/list/leftpush")public String leftPushToList(@RequestParam String key, @RequestParam String value) {redisService.pushToListLeft(key, value);return "值被推到列表的左侧";}// 向列表右侧推入值@GetMapping("/list/rightpush")public String rightPushToList(@RequestParam String key, @RequestParam String value) {redisService.pushToListRight(key, value);return "值被推到列表的右侧";}// 从列表左侧弹出值@GetMapping("/list/leftpop")public String leftPopFromList(@RequestParam String key) {return redisService.popFromListLeft(key);}// 从列表右侧弹出值@GetMapping("/list/rightpop")public String rightPopFromList(@RequestParam String key) {return redisService.popFromListRight(key);}// 获取列表中所有值@GetMapping("/list/getall")public List<Object> getAllFromList(@RequestParam String key) {return redisService.getList(key);}// Set操作@GetMapping("/set/add")public String addToSet(@RequestParam String key, @RequestParam String value) {redisService.addToSet(key, value);return "值已加入集合set";}@GetMapping("/set/members")public Set<Object> getSetMembers(@RequestParam String key) {return redisService.getSetMembers(key);}@GetMapping("/set/ismember")public boolean isMemberOfSet(@RequestParam String key, @RequestParam String value) {return redisService.isMemberOfSet(key, value);}@GetMapping("/set/remove")public String removeFromSet(@RequestParam String key, @RequestParam String value) {redisService.removeFromSet(key, value);return "值已从集合set移除";}// Sorted Set操作@GetMapping("/zset/add")public String addToSortedSet(@RequestParam String key, @RequestParam String value, @RequestParam double score) {redisService.addToSortedSet(key, value, score);return "值已加入有序集合sorted set";}@GetMapping("/zset/range")public Set<Object> getSortedSetRange(@RequestParam String key, @RequestParam long start, @RequestParam long end) {return redisService.getSortedSetRange(key, start, end);}@GetMapping("/zset/remove")public String removeFromSortedSet(@RequestParam String key, @RequestParam String value) {redisService.removeFromSortedSet(key, value);return "值已从有序集合sorted set移除";}// HyperLogLog操作@GetMapping("/hyperloglog/add")public String addToHyperLogLog(@RequestParam String key, @RequestParam String value) {redisService.addToHyperLogLog(key, value);return "Value added to HyperLogLog";}@GetMapping("/hyperloglog/count")public long countInHyperLogLog(@RequestParam String key) {return redisService.countInHyperLogLog(key);}// Bitmap操作@GetMapping("/bitmap/set")public String setBit(@RequestParam String key, @RequestParam long offset, @RequestParam boolean value) {redisService.setBit(key, offset, value);return "Bit set in bitmap";}@GetMapping("/bitmap/get")public boolean getBit(@RequestParam String key, @RequestParam long offset) {return redisService.getBit(key, offset);}// Geo操作//添加地理位置@GetMapping("/add-location")public String addLocation(@RequestParam String member, @RequestParam double longitude, @RequestParam double latitude) {redisService.addLocation(member, longitude, latitude);return "Location added.";}//查询附近的地点@GetMapping("/nearby")public List<GeoResult<RedisGeoCommands.GeoLocation<Object>>> getNearbyLocations(@RequestParam double longitude, @RequestParam double latitude, @RequestParam double radius) {return redisService.getNearbyLocations(longitude, latitude, radius);}//# 如果使用 Lettuce 作为客户端 lettuce//获取两地之间的距离@GetMapping("/distance")public Distance getDistance(@RequestParam String member1, @RequestParam String member2) {return redisService.getDistance(member1, member2);}
}

3. 测试操作

启动项目后,可以通过以下 URL 测试各种 Redis 数据类型的功能:

  • String操作

    • 设置值: http://localhost:8080/set?key=myKey&value=myValue

    • 获取值: http://localhost:8080/get?key=myKey

  • List操作

    • 向列表左侧推入值: http://localhost:8080/list/leftpush?key=myList&value=value1
    • 向列表右侧推入值: http://localhost:8080/list/rightpush?key=myList&value=value2
    • 从列表左侧弹出值: http://localhost:8080/list/leftpop?key=myList
    • 从列表右侧弹出值: http://localhost:8080/list/rightpop?key=myList
    • 获取列表中所有值: http://localhost:8080/list/getall?key=myList
  • Hash操作

    • 保存哈希数据: http://localhost:8080/hash/set?key=user:1001&field=name&value=一周一志程序员

    • 获取哈希数据: http://localhost:8080/hash/get?key=user:1001&field=name

    • 删除哈希字段: http://localhost:8080/hash/delete?key=user:1001&field=name

    • 获取所有哈希数据: http://localhost:8080/hash/getall?key=user:1001

  • Set 操作:

    • 添加成员到集合: http://localhost:8080/set/add?key=mySet&value=value1
    • 获取集合中的所有成员: http://localhost:8080/set/members?key=mySet
    • 检查成员是否在集合中: http://localhost:8080/set/ismember?key=mySet&value=value1
    • 删除集合中的成员: http://localhost:8080/set/remove?key=mySet&value=value1
  • Sorted Set 操作:

    • 添加成员到有序集合: http://localhost:8080/zset/add?key=myZSet&value=value1&score=1.0
    • 获取有序集合中的成员范围: http://localhost:8080/zset/range?key=myZSet&start=0&end=-1
    • 删除有序集合中的成员: http://localhost:8080/zset/remove?key=myZSet&value=value1
  • HyperLogLog 操作:

    • 添加成员到 HyperLogLog: http://localhost:8080/hyperloglog/add?key=myHLL&value=value1
    • 获取 HyperLogLog 的基数估算: http://localhost:8080/hyperloglog/count?key=myHLL
  • Bitmap 操作:

    • 设置 Bitmap 中某个位的值: http://localhost:8080/bitmap/set?key=myBitmap&offset=7&value=true
    • 获取 Bitmap 中某个位的值: http://localhost:8080/bitmap/get?key=myBitmap&offset=7
  • Geospatial 操作:

    • 添加地理位置:http://localhost:8080/add-location?member=location1&longitude=13.361389&latitude=38.115556
    • 查询附近的地点:http://localhost:8080/nearby?longitude=13.361389&latitude=38.115556&radius=10
    • 获取两地之间的距离: http://localhost:8080/distance?member1=location1&member2=location2

4. 总结

通过这些步骤,我们在 Spring Boot 项目中成功实现了对 Redis 各种数据类型(String、List、Set、Sorted Set、Bitmap、HyperLogLog 等)的操作。可以处理和管理 Redis 中的各种复杂数据结构,适应不同的应用场景需求。汇总到此结束。关注我一起为Java程序员蓄能,努力为职业生涯续航!

这篇关于SpringBoot依赖之Spring Data Redis的功能抽离公共服务的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1110755

相关文章

javax.net.ssl.SSLHandshakeException:异常原因及解决方案

《javax.net.ssl.SSLHandshakeException:异常原因及解决方案》javax.net.ssl.SSLHandshakeException是一个SSL握手异常,通常在建立SS... 目录报错原因在程序中绕过服务器的安全验证注意点最后多说一句报错原因一般出现这种问题是因为目标服务器

Java实现删除文件中的指定内容

《Java实现删除文件中的指定内容》在日常开发中,经常需要对文本文件进行批量处理,其中,删除文件中指定内容是最常见的需求之一,下面我们就来看看如何使用java实现删除文件中的指定内容吧... 目录1. 项目背景详细介绍2. 项目需求详细介绍2.1 功能需求2.2 非功能需求3. 相关技术详细介绍3.1 Ja

springboot项目中整合高德地图的实践

《springboot项目中整合高德地图的实践》:本文主要介绍springboot项目中整合高德地图的实践,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一:高德开放平台的使用二:创建数据库(我是用的是mysql)三:Springboot所需的依赖(根据你的需求再

spring中的ImportSelector接口示例详解

《spring中的ImportSelector接口示例详解》Spring的ImportSelector接口用于动态选择配置类,实现条件化和模块化配置,关键方法selectImports根据注解信息返回... 目录一、核心作用二、关键方法三、扩展功能四、使用示例五、工作原理六、应用场景七、自定义实现Impor

SpringBoot3应用中集成和使用Spring Retry的实践记录

《SpringBoot3应用中集成和使用SpringRetry的实践记录》SpringRetry为SpringBoot3提供重试机制,支持注解和编程式两种方式,可配置重试策略与监听器,适用于临时性故... 目录1. 简介2. 环境准备3. 使用方式3.1 注解方式 基础使用自定义重试策略失败恢复机制注意事项

SpringBoot整合Flowable实现工作流的详细流程

《SpringBoot整合Flowable实现工作流的详细流程》Flowable是一个使用Java编写的轻量级业务流程引擎,Flowable流程引擎可用于部署BPMN2.0流程定义,创建这些流程定义的... 目录1、流程引擎介绍2、创建项目3、画流程图4、开发接口4.1 Java 类梳理4.2 查看流程图4

一文详解如何在idea中快速搭建一个Spring Boot项目

《一文详解如何在idea中快速搭建一个SpringBoot项目》IntelliJIDEA作为Java开发者的‌首选IDE‌,深度集成SpringBoot支持,可一键生成项目骨架、智能配置依赖,这篇文... 目录前言1、创建项目名称2、勾选需要的依赖3、在setting中检查maven4、编写数据源5、开启热

苹果macOS 26 Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色

《苹果macOS26Tahoe主题功能大升级:可定制图标/高亮文本/文件夹颜色》在整体系统设计方面,macOS26采用了全新的玻璃质感视觉风格,应用于Dock栏、应用图标以及桌面小部件等多个界面... 科技媒体 MACRumors 昨日(6 月 13 日)发布博文,报道称在 macOS 26 Tahoe 中

Java对异常的认识与异常的处理小结

《Java对异常的认识与异常的处理小结》Java程序在运行时可能出现的错误或非正常情况称为异常,下面给大家介绍Java对异常的认识与异常的处理,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参... 目录一、认识异常与异常类型。二、异常的处理三、总结 一、认识异常与异常类型。(1)简单定义-什么是

Redis Cluster模式配置

《RedisCluster模式配置》:本文主要介绍RedisCluster模式配置,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录分片 一、分片的本质与核心价值二、分片实现方案对比 ‌三、分片算法详解1. ‌范围分片(顺序分片)‌2. ‌哈希分片3. ‌虚