redis(hash)使用场景

redis(hash)使用场景

1.‌用户信息存储

java 复制代码
@Service
public class UserInfoService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 保存完整用户信息
     */
    public void saveUserInfo(String userId, Map<String, Object> userInfo) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        hashOps.putAll("user:" + userId, userInfo);
    }
    
    /**
     * 获取完整用户信息
     */
    public Map<Object, Object> getUserInfo(String userId) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        return hashOps.entries("user:" + userId);
    }
    
    /**
     * 更新用户单个字段
     */
    public void updateUserField(String userId, String field, Object value) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        hashOps.put("user:" + userId, field, value);
    }
    
    /**
     * 获取用户特定字段值
     */
    public Object getUserField(String userId, String field) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        return hashOps.get("user:" + userId, field);
    }
    
    /**
     * 删除用户特定字段
     */
    public void deleteUserField(String userId, String field) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        hashOps.delete("user:" + userId, field);
    }
    
    /**
     * 检查用户字段是否存在
     */
    public boolean hasUserField(String userId, String field) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        return hashOps.hasKey("user:" + userId, field);
    }
    
    /**
     * 获取用户所有字段名
     */
    public Set<Object> getAllUserFields(String userId) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        return hashOps.keys("user:" + userId);
    }
    
    /**
     * 获取用户字段数量
     */
    public Long getUserFieldCount(String userId) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        return hashOps.size("user:" + userId);
    }
}

2.商品信息缓存

java 复制代码
@Service
public class ProductCacheService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 缓存商品详细信息
     */
    public void cacheProductInfo(String productId, Map<String, Object> productInfo) {
        redisTemplate.opsForHash().putAll("product:" + productId, productInfo);
        
        // 设置过期时间(24小时)
        redisTemplate.expire("product:" + productId, 24, TimeUnit.HOURS);
    }
    
    /**
     * 获取缓存的商品信息
     */
    public Map<Object, Object> getCachedProductInfo(String productId) {
        return redisTemplate.opsForHash().entries("product:" + productId);
    }
    
    /**
     * 更新商品价格
     */
    public void updateProductPrice(String productId, double price) {
        redisTemplate.opsForHash().put("product:" + productId, "price", price);
    }
    
    /**
     * 更新商品库存
     */
    public void updateProductStock(String productId, int stock) {
        redisTemplate.opsForHash().put("product:" + productId, "stock", stock);
    }
    
    /**
     * 批量更新商品字段
     */
    public void batchUpdateProductFields(String productId, Map<String, Object> updates) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        hashOps.putAll("product:" + productId, updates);
    }
    
    /**
     * 获取所有商品ID
     */
    public Set<Object> getAllProductIds() {
        return redisTemplate.keys("product:*");
    }
    
    /**
     * 删除商品缓存
     */
    public void deleteProductCache(String productId) {
        redisTemplate.delete("product:" + productId);
    }
}

3.购物车实现

java 复制代码
@Service
public class ShoppingCartService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 添加商品到购物车
     */
    public void addToCart(String userId, String productId, int quantity) {
        String cartKey = "cart:" + userId;
        redisTemplate.opsForHash().put(cartKey, productId, quantity);
    }
    
    /**
     * 从购物车移除商品
     */
    public void removeFromCart(String userId, String productId) {
        String cartKey = "cart:" + userId;
        redisTemplate.opsForHash().delete(cartKey, productId);
    }
    
    /**
     * 更新购物车商品数量
     */
    public void updateCartItemQuantity(String userId, String productId, int quantity) {
        String cartKey = "cart:" + userId;
        redisTemplate.opsForHash().put(cartKey, productId, quantity);
    }
    
    /**
     * 获取购物车所有商品
     */
    public Map<Object, Object> getCartItems(String userId) {
        String cartKey = "cart:" + userId;
        return redisTemplate.opsForHash().entries(cartKey);
    }
    
    /**
     * 清空购物车
     */
    public void clearCart(String userId) {
        String cartKey = "cart:" + userId;
        redisTemplate.delete(cartKey);
    }
    
    /**
     * 获取购物车商品数量
     */
    public Long getCartItemCount(String userId) {
        String cartKey = "cart:" + userId;
        return redisTemplate.opsForHash().size(cartKey);
    }
    
    /**
     * 检查购物车是否包含某商品
     */
    public boolean cartContainsProduct(String userId, String productId) {
        String cartKey = "cart:" + userId;
        return redisTemplate.opsForHash().hasKey(cartKey, productId);
    }
}

4.计数器集合

java 复制代码
@Service
public class CounterService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 原子性增加计数器
     */
    public Long incrementCounter(String key, String field, long delta) {
        return redisTemplate.opsForHash().increment(key, field, delta);
    }
    
    /**
     * 设置计数器初始值
     */
    public void setCounterValue(String key, String field, long value) {
        redisTemplate.opsForHash().put(key, field, value);
    }
    
    /**
     * 获取计数器值
     */
    public Long getCounterValue(String key, String field) {
        Object value = redisTemplate.opsForHash().get(key, field);
        return value != null ? Long.parseLong(value.toString()) : 0;
    }
    
    /**
     * 批量增加多个计数器
     */
    public void batchIncrementCounters(String key, Map<String, Long> increments) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        for (Map.Entry<String, Long> entry : increments.entrySet()) {
            hashOps.increment(key, entry.getKey(), entry.getValue());
        }
    }
    
    /**
     * 获取所有计数器值
     */
    public Map<Object, Object> getAllCounterValues(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
}

5.配置信息存储

java 复制代码
@Service
public class ConfigService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 保存系统配置
     */
    public void saveConfig(String configKey, Map<String, Object> config) {
        redisTemplate.opsForHash().putAll(configKey, config);
    }
    
    /**
     * 获取配置值
     */
    public Object getConfigValue(String configKey, String field) {
        return redisTemplate.opsForHash().get(configKey, field);
    }
    
    /**
     * 更新配置字段
     */
    public void updateConfigField(String configKey, String field, Object value) {
        redisTemplate.opsForHash().put(configKey, field, value);
    }
    
    /**
     * 删除配置字段
     */
    public void deleteConfigField(String configKey, String field) {
        redisTemplate.opsForHash().delete(configKey, field);
    }
    
    /**
     * 获取所有配置字段
     */
    public Set<Object> getAllConfigFields(String configKey) {
        return redisTemplate.opsForHash().keys(configKey);
    }
    
    /**
     * 检查配置字段是否存在
     */
    public boolean hasConfigField(String configKey, String field) {
        return redisTemplate.opsForHash().hasKey(configKey, field);
    }
    
    /**
     * 批量更新配置
     */
    public void batchUpdateConfig(String configKey, Map<String, Object> updates) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        hashOps.putAll(configKey, updates);
    }
}

6.批量操作

java 复制代码
@Service
public class BatchOperationService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 批量设置多个字段
     */
    public void batchSetFields(String key, Map<String, Object> fields) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        hashOps.putAll(key, fields);
    }
    
    /**
     * 批量获取多个字段值
     */
    public Map<String, Object> batchGetFields(String key, Set<String> fields) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash());
        return hashOps.multiGet(key, fields);
    }
    
    /**
     * 批量删除多个字段
     */
    public void batchDeleteFields(String key, Set<String> fields) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash());
        for (String field : fields) {
            hashOps.delete(key, field);
        }
    }
    
    /**
     * 批量检查字段存在性
     */
    public Map<String, Boolean> batchCheckFields(String key, Set<String> fields) {
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash());
        Map<String, Boolean> results = new HashMap<>();
        for (String field : fields) {
            results.put(field, hashOps.hasKey(key, field);
        }
        return results;
    }
}

相关推荐
孟健15 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞16 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽19 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程1 天前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪1 天前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook1 天前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田2 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战2 天前
Pydantic配置管理最佳实践(一)
python