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

java语言里redis在项目中使用场景,每个场景的样例代码

Redis是一款高性能的NoSQL数据库,常被用于缓存、消息队列、计数器、分布式锁等场景。以下是50个Redis在项目中使用的场景以及对应的样例代码和详细说明:

##1、缓存:将查询结果缓存在Redis中,下次查询时直接从缓存中获取,减少数据库查询次数。

// 设置缓存
redisTemplate.opsForValue().set("key", "value", Duration.ofMinutes(10));
// 获取缓存
String value = redisTemplate.opsForValue().get("key");

##2、分布式锁:多个进程/线程同时访问一个资源时,使用Redis实现分布式锁,保证同一时刻只有一个进程/线程访问该资源。

// 加锁
Boolean locked = redisTemplate.opsForValue().setIfAbsent("lock_key", "lock_value", Duration.ofSeconds(30));
if (locked) {try {// 执行业务逻辑} finally {// 释放锁redisTemplate.delete("lock_key");}
}

##3、计数器:实现用户访问量、文章浏览量等计数功能。

// 计数器加1
redisTemplate.opsForValue().increment("counter_key");
// 获取计数器值
Long counter = redisTemplate.opsForValue().get("counter_key");
队列:实现任务异步处理、消息队列等功能。// 生产者向队列中添加消息
redisTemplate.opsForList().leftPush("queue_key", "message");
// 消费者从队列中获取消息
String message = redisTemplate.opsForList().rightPop("queue_key");
发布/订阅:实现实时消息推送、事件通知等功能。// 发布消息
redisTemplate.convertAndSend("channel", "message");
// 订阅消息
redisTemplate.execute(new RedisCallback<Void>() {@Overridepublic Void doInRedis(RedisConnection connection) throws DataAccessException {connection.subscribe((message, pattern) -> {// 处理接收到的消息}, "channel".getBytes());return null;}
});

##4、分布式缓存:多节点部署时,使用Redis实现分布式缓存,提高缓存命中率。

// 设置缓存
redisTemplate.opsForValue().set("key", "value", Duration.ofMinutes(10));
// 获取缓存
String value = redisTemplate.opsForValue().get("key");
排行榜:实现用户积分排行榜、文章点赞排行榜等功能。// 新增用户积分
redisTemplate.opsForZSet().add("ranking_key", "user_id", score);
// 获取用户排名
Long rank = redisTemplate.opsForZSet().reverseRank("ranking_key", "user_id");

##5、搜索引擎:使用Redis实现搜索引擎的缓存、索引等功能。

// 将搜索结果缓存到Redis中
redisTemplate.opsForValue().set("search_key", "search_result", Duration.ofMinutes(10));
// 从Redis中获取搜索结果
String searchResult = redisTemplate.opsForValue().get("search_key");
分布式事务:使用Redis实现分布式事务,保证多个操作的原子性。// 开启事务
redisTemplate.multi();
// 执行多个操作
redisTemplate.opsForValue().set("key1", "value1");
redisTemplate.opsForValue().set("key2", "value2");
// 提交事务
List<Object> results = redisTemplate.exec();

##6、地理位置:使用Redis实现地理位置相关功能,如附近的人、附近的商家等。

// 添加地理位置信息
redisTemplate.opsForGeo().add("location_key", new Point(116.405285, 39.904989), "user_id");
// 获取附近的人
GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo().radius("location_key", new Circle(new Point(116.405285, 39.904989), new Distance(1, Metrics.KILOMETERS)));

##7、聊天室:使用Redis实现聊天室功能,支持实时聊天、消息记录等。

// 加入聊天室
redisTemplate.opsForSet().add("chat_room_key", "user_id");
// 发送消息
redisTemplate.opsForList().leftPush("chat_message_key", "message");
// 获取聊天室成员列表
Set<String> members = redisTemplate.opsForSet().members("chat_room_key");
// 获取聊天记录
List<String> messages = redisTemplate.opsForList().range("chat_message_key", 0, -1);
数据缓存:使用Redis实现数据缓存,提高系统性能。// 设置缓存
redisTemplate.opsForValue().set("key", "value", Duration.ofMinutes(10));
// 获取缓存
String value = redisTemplate.opsForValue().get("key");

##8、验证码:使用Redis实现验证码功能,支持短信验证码、图形验证码等。

// 生成验证码
String code = generateCode();
// 将验证码缓存到Redis中
redisTemplate.opsForValue().set("code_key", code, Duration.ofMinutes(5));
// 发送验证码
sendCode(code);
// 验证验证码
String storedCode = redisTemplate.opsForValue().get("code_key");
if (code.equals(storedCode)) {// 验证通过
} else {// 验证失败
}
文件上传:使用Redis实现文件上传功能,支持分片上传、断点续传等。// 上传文件
byte[] fileData = getFileData();
redisTemplate.opsForValue().set("file_key", fileData);
// 下载文件
byte[] fileData = redisTemplate.opsForValue().get("file_key");

##9、限流:使用Redis实现限流功能,控制请求流量。

// 限制每秒最多处理10个请求
String key = "limit_key:" + System.currentTimeMillis() / 1000;
Long count = redisTemplate.opsForValue().increment(key, 1);
if (count == 1) {redisTemplate.expire(key, 1, TimeUnit.SECONDS);
} else if (count > 10) {throw new RuntimeException("too many requests");
}

##10、日志:使用Redis实现日志功能,支持日志记录、日志查询等。

// 记录日志
redisTemplate.opsForList().leftPush("log_key", "log_message");
// 查询日志
List<String> logs = redisTemplate.opsForList().range("log_key", 0, -1);

##11、分布式缓存锁:使用Redis实现分布式缓存锁,避免缓存雪崩。

// 加锁
Boolean locked = redisTemplate.opsForValue().setIfAbsent("lock_key", "lock_value", Duration.ofMinutes(10));
if (locked) {try {// 从缓存中获取数据String data = redisTemplate.opsForValue().get("data_key");if (data == null) {// 缓存中没有数据,从数据库中获取data = getDataFromDatabase();// 将数据缓存到Redis中redisTemplate.opsForValue().set("data_key", data, Duration.ofMinutes(10));}} finally {// 释放锁redisTemplate.delete("lock_key");}
}

##12、短链接:使用Redis实现短链接功能,将长链接转换为短链接。

// 生成短链接
String shortUrl = generateShortUrl();
// 将短链接与长链接映射关系缓存到Redis中
redisTemplate.opsForValue().set("url_mapping_key:" + shortUrl, "long_url", Duration.ofDays(30));
// 获取长链接
String longUrl = redisTemplate.opsForValue().get("url_mapping_key:" + shortUrl);

##13、会话管理:使用Redis实现会话管理功能,支持单点登录、会话过期等。

// 将会话信息缓存到Redis中
redisTemplate.opsForValue().set("session_key:" + sessionId, "user_id", Duration.ofMinutes(30));
// 验证会话是否有效
String userId = redisTemplate.opsForValue().get("session_key:" + sessionId);
if (userId == null) {// 会话无效
} else {// 会话有效
}

##14、数据统计:使用Redis实现数据统计功能,支持用户行为统计、业务数据统计等。

// 统计用户行为
redisTemplate.opsForValue().increment("behavior_key:" + userId + ":click", 1);
// 获取用户行为统计结果
Long clickCount = redisTemplate.opsForValue().get("behavior_key:" + userId + ":click");

##15、频率控制:使用Redis实现频率控制功能,控制用户请求频率。

// 限制每分钟最多处理10个请求
String key = "limit_key:" + System.currentTimeMillis() / 60000;
Long count = redisTemplate.opsForValue().increment(key, 1);
if (count == 1) {redisTemplate.expire(key, 1, TimeUnit.MINUTES);
} else if (count > 10) {throw new RuntimeException("too many requests");
}

##16、倒计时:使用Redis实现倒计时功能,支持秒杀活动、限时抢购等。

// 设置倒计时
redisTemplate.opsForValue().set("countdown_key", "countdown_value", Duration.ofSeconds(60));
// 获取倒计时剩余时间
Long remainingTime = redisTemplate.opsForValue().getOperations().getExpire("countdown_key");

##17、活动抽奖:使用Redis实现活动抽奖功能,支持随机抽奖、概率抽奖等。

// 添加奖品
redisTemplate.opsForList().rightPushAll("prize_key", "prize1", "prize2", "prize3");
// 抽奖
String prize = redisTemplate.opsForList().leftPop("prize_key");
分布式任务调度:使用Redis实现分布式任务调度,支持定时任务、
接下来再举例java语言里redis在项目中使用场景,每个场景的样例代码,列出二十个项目场景,详细说明

##18、分布式缓存更新:使用Redis实现分布式缓存更新,保证缓存数据的一致性。

// 更新数据
updateData();
// 将缓存标记为失效
redisTemplate.delete("cache_key");
// 在其他节点上查询缓存时发现已失效,从数据库中重新加载数据并更新缓存

##19、分布式事务消息:使用Redis实现分布式事务消息,支持跨服务的事务消息处理。

// 提交事务消息
redisTemplate.execute(new SessionCallback<Void>() {@Overridepublic Void execute(RedisOperations operations) throws DataAccessException {operations.multi();operations.opsForValue().set("message_key", "message");operations.opsForSet().add("message_ids_key", "message_id");operations.exec();return null;}
});
// 处理事务消息
redisTemplate.execute(new SessionCallback<Void>() {@Overridepublic Void execute(RedisOperations operations) throws DataAccessException {operations.watch("message_ids_key");Set<String> messageIds = operations.opsForSet().members("message_ids_key");if (messageIds.contains("message_id")) {operations.multi();// 处理消息operations.opsForValue().get("message_key");operations.opsForSet().remove("message_ids_key", "message_id");operations.exec();}return null;}
});

##20、分布式锁实现限流:使用Redis实现分布式锁实现限流功能,控制请求流量。

// 尝试加锁
Boolean locked = redisTemplate.opsForValue().setIfAbsent("lock_key", "lock_value", Duration.ofSeconds(30));
if (locked) {try {// 限制每秒最多处理10个请求String key = "limit_key:" + System.currentTimeMillis() / 1000;Long count = redisTemplate.opsForValue().increment(key, 1);if (count == 1) {redisTemplate.expire(key, 1, TimeUnit.SECONDS);} else if (count > 10) {throw new RuntimeException("too many requests");}} finally {// 释放锁redisTemplate.delete("lock_key");}
}

##21、分布式锁实现幂等性:使用Redis实现分布式锁实现幂等性,避免重复操作。

// 尝试加锁
Boolean locked = redisTemplate.opsForValue().setIfAbsent("lock_key", "lock_value", Duration.ofSeconds(30));
if (locked) {try {// 检查是否已经处理过String key = "processed_key:" + id;Boolean processed = redisTemplate.opsForValue().get(key) != null;if (!processed) {// 处理数据processData();// 标记为已处理redisTemplate.opsForValue().set(key, "processed", Duration.ofDays(1));}} finally {// 释放锁redisTemplate.delete("lock_key");}
}

##22、分布式事务消息实现幂等性:使用Redis实现分布式事务消息实现幂等性,避免重复操作。

// 提交事务消息
redisTemplate.execute(new SessionCallback<Void>() {@Overridepublic Void execute(RedisOperations operations) throws DataAccessException {operations.watch("message_ids_key");Set<String> messageIds = operations.opsForSet().members("message_ids_key");if (!messageIds.contains("message_id")) {operations.multi();// 提交消息operations.opsForValue().set("message_key", "message");operations.opsForSet().add("message_ids_key", "message_id");operations.exec();}return null;}
});
// 处理事务消息
redisTemplate.execute(new SessionCallback<Void>() {@Overridepublic Void execute(RedisOperations operations) throws DataAccessException {operations.watch("message_ids_key");Set<String> messageIds = operations.opsForSet().members("message_ids_key");if (messageIds.contains("message_id")) {operations.multi();// 处理消息operations.opsForValue().get("message_key");operations.opsForSet().remove("message_ids_key", "message_id");operations.exec();}return null;}
});

##23、分布式缓存更新实现幂等性:使用Redis实现分布式缓存更新实现幂等性,避免重复操作。

// 尝试加锁
Boolean locked = redisTemplate.opsForValue().setIfAbsent("lock_key", "lock_value", Duration.ofSeconds(30));
if (locked) {try {// 检查是否已经处理过String key = "processed_key:" + id;Boolean processed = redisTemplate.opsForValue().get(key) != null;if (!processed) {// 更新数据updateData();// 将缓存标记为失效redisTemplate.delete("cache_key");// 标记为已处理redisTemplate.opsForValue().set(key, "processed", Duration.ofDays(1));}} finally {// 释放锁redisTemplate.delete("lock_key");}
}

##24、分布式事务消息实现延迟处理:

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;public class DelayedMessageQueue {private JedisPool jedisPool;public DelayedMessageQueue() {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();jedisPoolConfig.setMaxTotal(100);jedisPoolConfig.setMaxIdle(20);jedisPoolConfig.setMinIdle(10);jedisPoolConfig.setTestOnBorrow(true);jedisPool = new JedisPool(jedisPoolConfig, "localhost", 6379);}public void addMessage(String message, long delay) {try (Jedis jedis = jedisPool.getResource()) {long timestamp = System.currentTimeMillis() + delay;jedis.zadd("delayed_messages", timestamp, message);}}public void processMessages() {try (Jedis jedis = jedisPool.getResource()) {while (true) {long timestamp = System.currentTimeMillis();// 获取所有需要处理的消息Set<String> messages = jedis.zrangeByScore("delayed_messages", 0, timestamp, 0, 1);if (messages.isEmpty()) {// 没有需要处理的消息,等待一段时间再次尝试Thread.sleep(1000);continue;}String message = messages.iterator().next();// 处理消息System.out.println("Processing message: " + message);// 从延迟消息队列中删除已经处理的消息jedis.zrem("delayed_messages", message);}} catch (InterruptedException e) {Thread.currentThread().interrupt();}}public static void main(String[] args) {DelayedMessageQueue messageQueue = new DelayedMessageQueue();messageQueue.addMessage("Hello, world!", 5000); // 5秒后处理消息messageQueue.processMessages();}
}

这个样例代码中,我们使用了Redis的有序集合来实现延迟消息队列。当我们添加消息时,我们将消息和一个时间戳加入到有序集合中,
时间戳为当前时间加上延迟时间。在处理消息时,我们获取所有需要处理的消息,即时间戳小于当前时间的所有消息,然后依次处理它们,
并从延迟消息队列中删除已经处理的消息。如果没有需要处理的消息,我们等待一段时间再次尝试。

http://www.lryc.cn/news/68566.html

相关文章:

  • Mongo集合操作
  • ConvTranspose2d 的简单例子理解
  • 酒精和肠内外健康:有帮助还是有害?
  • SylixOS Shell下操作环境变量方法
  • 【dfs解决分组问题-两道例题——供佬学会!】(A元素是放在已经存在的组别中,还是再创建一个更好?--小孩子才做选择,dfs直接两种情况都试试)
  • 使用Hexo在Github上搭建个人博客
  • 【面试题】面试官:说说你对 CSS 盒模型的理解
  • 【ROS2】学习笔记
  • Springboot +Flowable,流程表单应用之外置表单(JSON形式)(二)
  • JavaScript如何使用if语句
  • XSS攻击以及java应对措施
  • yolo 训练
  • 谷歌chrome浏览器升级新版后字体显示不清楚解决方案
  • 在外包干了三年,我废了……不吹不黑!
  • 【Vue】学习笔记-消息的订阅与发布
  • 大疆无人机 MobileSDK(遥控器/手机端)开发 v5版<1>
  • azkaban介绍
  • 自学黑客(网络安全)必学内容
  • Java每日一练(20230518) 移除元素、跳跃游戏II、复原IP地址
  • diff命令和vimdiff命令
  • AcWing 797.差分(C++)
  • Python每日一练(20230515) 只出现一次的数字 I\II\III
  • 基于【EasyDL】【图像分类】实现农作物病害识别小程序
  • 元宇宙又“死”了!Epic老板:你当6亿用户是摆设?
  • 阶段小结2022
  • linux0.12-8-11-vsprintf.c
  • Node.js 与 WebAssembly
  • OpenCL编程指南-4.4矢量操作符
  • 索洛模型(二)
  • 【多微电网】基于粒子群优化算法的面向配电网的多微电网协调运行与优化(Matlab代码实现)