Redis在职场中的实战应用,你绝对不能错过!
发表时间: 2024-03-07 10:49
当涉及到在工作中使用 Redis 时,下面是一些具体的场景和相应的例子:
import redis.clients.jedis.Jedis;public class UserCache { private Jedis jedis = new Jedis("localhost"); public String getUserInfo(int userId) { String userInfo = jedis.get("user:" + userId); if (userInfo == null) { // 从数据库获取用户信息 userInfo = db.queryUserInfo(userId); // 将用户信息存入 Redis,并设置过期时间 jedis.setex("user:" + userId, 3600, userInfo); } return userInfo; }}
public class ProductCache { private Jedis jedis = new Jedis("localhost"); public String getProductInfo(int productId) { String productInfo = jedis.get("product:" + productId); if (productInfo == null) { productInfo = db.queryProductInfo(productId); jedis.setex("product:" + productId, 600, productInfo); } return productInfo; }}
public class PageVisitCounter { private Jedis jedis = new Jedis("localhost"); public void recordPageVisit(int pageId) { jedis.incr("page:" + pageId + ":visits"); }}
public class LikeCounter { private Jedis jedis = new Jedis("localhost"); public void likePost(int userId, int postId) { jedis.hincrBy("post:" + postId + ":likes", String.valueOf(userId), 1); }}
public class StockManager { private Jedis jedis = new Jedis("localhost"); public void reduceStockWithLock(int productId, int quantity) { String lockKey = "lock:reduce_stock:" + productId; String lockValue = "locked"; // 尝试获取分布式锁 String result = jedis.set(lockKey, lockValue, "NX", "EX", 10); if ("OK".equals(result)) { // 执行库存扣减操作 // ... // 释放锁 jedis.del(lockKey); } }}
public class FormHandler { private Jedis jedis = new Jedis("localhost"); public void handleFormSubmission(FormData formData) { String lockKey = "lock:form_submission:" + formData.getUserId(); String lockValue = "locked"; String result = jedis.set(lockKey, lockValue, "NX", "EX", 60); if ("OK".equals(result)) { // 处理表单提交 // ... // 释放锁 jedis.del(lockKey); } }}
import redis.clients.jedis.Jedis;import java.util.Set;public class ArticleRanking { private Jedis jedis = new Jedis("localhost"); public void incrementArticleReadCount(int articleId) { jedis.zincrby("article_ranking", 1, "article:" + articleId); } public Set<String> getTopArticles(int count) { return jedis.zrevrange("article_ranking", 0, count - 1); }}
import redis.clients.jedis.Jedis;import java.util.Set;public class PlayerScoreRanking { private Jedis jedis = new Jedis("localhost"); public void incrementPlayerScore(int playerId, int score) { jedis.zincrby("player_score_ranking", score, "player:" + playerId); } public Set<String> getTopPlayers(int count) { return jedis.zrevrange("player_score_ranking", 0, count - 1); }}
import redis.clients.jedis.Jedis;public class AsyncTaskQueue { private Jedis jedis = new Jedis("localhost"); public void enqueueTask(String task) { jedis.lpush("async_task_queue", task); } public String dequeueTask() { return jedis.brpop(0, "async_task_queue").get(1); }}
import redis.clients.jedis.Jedis;public class EventPublisher { private Jedis jedis = new Jedis("localhost"); public void publishEvent(String channel, String event) { jedis.publish(channel, event); }}public class EventSubscriber extends JedisPubSub { private Jedis jedis = new Jedis("localhost"); public void subscribeToChannel(String channel) { jedis.subscribe(this, channel); } @Override public void onMessage(String channel, String message) { // 处理接收到的事件消息 System.out.println("Received event: " + message); }}
场景描述: 防止恶意请求或者突发流量对系统造成影响,可以使用 Redis 实现限流控制。
import redis.clients.jedis.Jedis;public class RequestRateLimiter { private Jedis jedis = new Jedis("localhost"); public boolean isAllowed(String ipAddress, int maxRequestsPerMinute) { String key = "rate_limit:" + ipAddress + ":" + System.currentTimeMillis() / 60000; long count = jedis.incr(key); if (count == 1) { jedis.expire(key, 60); // 设置过期时间为一分钟 } return count <= maxRequestsPerMinute; }}
示例: 使用 Redis 的计数器或漏桶算法实现接口访问频率限制、短信验证码发送限制、防火墙规则等,通过监控请求频率并拒绝超出限制的请求。