All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.github.coffee330501.utils.RedisUtil Maven / Gradle / Ivy

package io.github.coffee330501.utils;

import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component("interCallRedisUtil")
public class RedisUtil {
    @Resource
    private RedisTemplate redisTemplate;

    public boolean setNx(final String key, final int expireSeconds) {
        return (boolean) redisTemplate.execute((RedisCallback) connection -> {
            StringRedisSerializer serializer = new StringRedisSerializer();
            boolean success = connection.setNX(serializer.serialize(key), serializer.serialize("true"));
            if (success) {
                connection.expire(serializer.serialize(key), expireSeconds);
            }
            connection.close();
            return success;
        });
    }
}