Redis(RedisTemplate)使用hash哈希


RedisTemplate配置:https://www.cnblogs.com/weibanggang/p/10188682.html

package com.wbg.springRedis.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestHash {
    static RedisTemplate redisTemplate = null;

    public static void main(String[] args) {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-redis.xml");
        redisTemplate = applicationContext.getBean(RedisTemplate.class);
        String key = "hash";
        Map<String, String> map = new HashMap<>();
        map.put("filed1", "value1");
        map.put("filed2", "value2");
        //相當於hmset
        redisTemplate.opsForHash().putAll(key, map);
        //相當於hset
        redisTemplate.opsForHash().put(key, "filed3", "10");
        //相當於hexists key filed //是否存在
        boolean bool = redisTemplate.opsForHash().hasKey(key, "filed3");
        System.out.println(bool);
        //相當於hgetall {filed1=value1, filed2=value2, filed3=10}獲取所有hash的鍵=值
        Map map1 = redisTemplate.opsForHash().entries(key);
        System.out.println(map1);
        //hincrby //加5  如果是原數據是float類型會異常
        redisTemplate.opsForHash().increment(key, "filed3", 5);
        pring("filed3");
        //hincrbyfloat 2.3
        redisTemplate.opsForHash().increment(key, "filed3", 2.2);
        pring("filed3");
        //hvals [value1, value2, 17.199999999999999] 獲取所有的value
        System.out.println(redisTemplate.opsForHash().values(key));
        //hkeys [filed1, filed2, filed3] //獲取所有的鍵
        System.out.println(redisTemplate.opsForHash().keys(key));
        List<String> list = new ArrayList<>();
        list.add("filed1");
        list.add("filed2");
        //hmget  [value1, value2] // 獲取對於的鍵  值 沒有就返回空
        System.out.println(redisTemplate.opsForHash().multiGet(key, list));
        //hsetnx 不存在的時候才會設置進入true   否則返回false
        System.out.println(redisTemplate.opsForHash().putIfAbsent(key,"filed4", "value4"));
        //hdel 返回刪除個數
        System.out.println(redisTemplate.opsForHash().delete(key,"filed1","filed2","filed6"));

    }

    public static void pring(String filed) {
        System.out.println(redisTemplate.opsForHash().get("hash", filed));
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM