1. 程式人生 > 實用技巧 >Java使用Lettuce操作redis

Java使用Lettuce操作redis

maven包

# 包含了lettuce jar
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

LettuceRedisUtils

package com.meeno.chemical.common.redis;

import com.alibaba.fastjson.JSONObject;
import com.meeno.chemical.common.constants.Constants;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import org.springframework.boot.autoconfigure.cache.CacheProperties;

import java.util.List;

/**
 * @description: lettuceRedis工具類
 * @author: Wzq
 * @create: 2020-08-05 19:34
 */
public class LettuceRedisUtils {

    /**
     * 獲取command
     * @return
     */
    private  static RedisURI getRedisUri(){
        String host = RedisConfig.host;
        Integer port = RedisConfig.port;
        String password = RedisConfig.password;
        Integer database = RedisConfig.database;
        RedisURI redisUri = RedisURI.Builder.redis(host)
                .withPort(port)
                .withPassword(password)
                .withDatabase(database)
                .build();


        return redisUri;
    }


    /**
     * 匹配key 返回匹配的key列表
     * @param keys
     * @return
     */
    public static List<String> keys(String keys){

        RedisURI redisUri = getRedisUri();

        RedisClient client = RedisClient.create(redisUri);

        StatefulRedisConnection<String, String> connect = client.connect();
        RedisCommands<String, String> commands = connect.sync();

        List<String> keyList = commands.keys(keys);

        connect.close();
        client.shutdown();


        return keyList;
    }

    /**
     * 設定key,和value 失效時間為一天
     * @param key
     * @param value
     */
    public static void set(String key,String value){
        RedisURI redisUri = getRedisUri();

        RedisClient client = RedisClient.create(redisUri);

        StatefulRedisConnection<String, String> connect = client.connect();
        RedisCommands<String, String> commands = connect.sync();
        commands.setex(key, Constants.DAY_SECOND ,value);

        connect.close();
        client.shutdown();
    }

    /**
     * 設定key,和value 失效時間為一天
     * @param key
     * @param value
     */
    public static void set(String key, Object value){
        String valueStr = null;
        if(value != null){
            valueStr = JSONObject.toJSONString(value);
        }
        set(key, valueStr);
    }

    public static String get(String key){

        RedisURI redisUri = getRedisUri();

        RedisClient client = RedisClient.create(redisUri);

        StatefulRedisConnection<String, String> connect = client.connect();
        RedisCommands<String, String> commands = connect.sync();

        String s = commands.get(key);

        connect.close();
        client.shutdown();


        return s;
    }



}