redis學習筆記4: 在Java中操作Redis

HIK4RU44發表於2024-05-14

redis學習筆記4: 在Java中操作Redis


Redis的Java客戶端

  • Jedis [命令和原生Redis基本相同]

  • Lettuce [效能高效]

  • Spring Date Redis [可以在Spring專案中使用, 簡化操作]


Spring Date Redis使用方式

匯入maven座標

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>3.2.4</version>
</dependency>

其他版本管理方式

<properties>
    <redis>3.2.4</redis>
</properties>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>${redis}</version>
</dependency>

配置Redis資料來源

application-dev

spring: #是spirng分級下的
 redis:
  host: localhost
  port: 6379
  password: 123456 #redis 5.0密碼需要被""包裹
  database: 0 #一共有16個庫 DB0 不同資料庫的資料是完全隔離的 [在有些情況可能不被識別]

application

spring:
 redis:
  host: ${spring.redis.host}
  port: ${spring.redis.port}
  password: ${spring.redis.password}}   
  database: ${spring.redis.database}

編寫相關配置類, 建立RedisTemplate物件

@Configuration
@Slf4j
public class RedisConfiguration {
    @Bean //將第三方類交給IOC容器管理
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        log.info("開始建立redis模板類");
        RedisTemplate redisTemplate = new RedisTemplate();
        //設定key的序列化器, 預設為JdkSerializationRedisSerializer
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //設定redis連線工廠物件
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }

透過RedisTemplate物件操作Redis

string

public void testString(){
    redisTemplate.opsForValue().set("name","小明");

    //get key
    String name = (String) redisTemplate.opsForValue().get("name");
    String city2 = (String) redisTemplate.opsForValue().get("city2");
    System.out.println(name);
    System.out.println(city2);

    //SETEX key seconds value  設定過期時間為seconds的key
    //SETEX code 3 1234
    redisTemplate.opsForValue().set("code","1234",10, TimeUnit.SECONDS); //使用列舉類寫時間單位

    //setNX 當key不存在時建立
    //redis的string和java的String不是完全不同, 最後都會轉化成redis字串儲存
    redisTemplate.opsForValue().setIfAbsent("lock",1);
    redisTemplate.opsForValue().setIfAbsent("lock",2);
}

hash

//    @Test
public void testHash() {
    //hset hget hkeys hvals
    HashOperations hashOperations = redisTemplate.opsForHash();
    //hset key filed value
    hashOperations.put("100","name","tom");
    hashOperations.put("100","age","20");
    hashOperations.put("100","gender","male");

    //hget key field
    String name = (String) hashOperations.get("100","name");
    System.out.println(name);

    //hkeys key
    Set keys = hashOperations.keys("100");
    System.out.println(keys);

    //hvals key
    List values = hashOperations.values("100");
    System.out.println(values);

    //hdel key field
    hashOperations.delete("100","gender");
}

set

public void testSet1(){
    SetOperations setOperations = redisTemplate.opsForSet();

    //sadd 插入新資料
    setOperations.add("set1","aa","bb","cc");

    //smembers 遍歷
    setOperations.members("set1");

    //scard 元素數量
    Long size = setOperations.size("set1");
    System.out.println(size);

    //sinter 交集
    System.out.println(setOperations.intersect("set1", "set2"));

    //sunion 並集
    System.out.println(setOperations.union("set1", "set2"));

    //srem 刪除
    setOperations.remove("set1","aa","bb");
}

list

public void testList(){
    ListOperations listOperations = redisTemplate.opsForList();

    //Lpush 左壓棧
    listOperations.leftPush("mylist","aa");
    listOperations.leftPush("mylist","bb");
    listOperations.leftPush("mylist","cc");
    listOperations.leftPush("mylist","dd");

    //Llen 元素數量
    System.out.println(listOperations.size("mylist"));

    //Lrange 遍歷
    System.out.println(listOperations.range("mylist", 0, -1));

    //Rpop 右彈出
    listOperations.rightPop("mylist");

    //Llen 元素數量
    System.out.println(listOperations.size("mylist"));
}

zset

public void testZSet(){
    ZSetOperations zSetOperations = redisTemplate.opsForZSet();

    //zadd key value score 向zset插入資料
    zSetOperations.add("zset1","a",19);

    //zrange 遍歷zset
    System.out.println(zSetOperations.range("zset1", 0, -1));

    //zrange key start end withScores  遍歷zset並顯示分數
    System.out.println(zSetOperations.rangeByScoreWithScores("myset1", 0, -1));

    //zincreby 為指定key的分數新增一個增量
    zSetOperations.incrementScore("zset1","c",10);

    //zrem 刪除指定key
    zSetOperations.remove("zset1","a","b");
}

通用命令操作

public void testCommon(){
    //keys * 查詢所有key
    Set keys = redisTemplate.keys("*");
    System.out.println(keys);

    //exists 查詢指定key是否存在
    Boolean name = redisTemplate.hasKey("name");

    //type 查詢keys集合中所有資料的型別
    for (Object key : keys) {
        System.out.println(redisTemplate.type(key));
    }

    //del 根據key刪除資料
    redisTemplate.delete("mylist");
}

其他的

在圖形化介面key正常, valule顯示亂碼, 透過java輸出是正常的

不設定序列化器, 會使用預設的序列化器, key亂碼, 可以在java中查詢到

相關文章