RedisConfig配置

java 复制代码
package io.renren.common.redis;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * Redis配置
 **/
@Configuration
public class RedisConfig {
    @Resource
    private RedisConnectionFactory factory;

    // 锁前缀
    private static final String SCHEMA_PREFIX = "redis://";
    @Bean
    public Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer(){
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        return jackson2JsonRedisSerializer;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(factory);

        return redisTemplate;
    }

    /**
     * 创建 RedissonClient,注入IOC容器
     */
    @Bean
    public RedissonClient redissonClient(RedisProperties redisProperties) {
        Config config = new Config();
        //单点redis
        SingleServerConfig singleServerConfig = config.useSingleServer().
                setAddress(SCHEMA_PREFIX + redisProperties.getHost() + ":" + redisProperties.getPort());
        if (StringUtils.hasText(redisProperties.getPassword())) {
            singleServerConfig.setPassword(redisProperties.getPassword());
        }
        singleServerConfig.setTimeout((int) redisProperties.getTimeout().toMillis());
        singleServerConfig.setPingConnectionInterval(30000);
        singleServerConfig.setDatabase(redisProperties.getDatabase());
        // 超时时间
        long lockWatchTimeOut = 3000;
        config.setLockWatchdogTimeout(lockWatchTimeOut);
        return Redisson.create(config);
    }
java 复制代码
@Component
public class RedissonLock {
    @Autowired
    private RedissonClient redissonClient;

    private static final String LOCK_PREFIX = "lock:";

    /**
     * 阻塞方式获取锁
     * @param key
     * @param expireTime
     * @return
     */
    public RLock lock(String key,Integer expireTime){
        //可重入锁
        RLock lock = redissonClient.getLock(LOCK_PREFIX + key);
        //lock.lock(expireTime, TimeUnit.SECONDS); //阻塞方式获取锁,设置过期时间
        lock.lock();
        return lock;
    }


    /**
     * 非阻塞方式获取锁
     * @param key
     */
    public Boolean tryLock(String key){
        try {
            RLock lock = redissonClient.getLock(LOCK_PREFIX + key);

            return lock.tryLock(5L, TimeUnit.SECONDS); //非阻塞方式获取锁,设置在指定时间内失败重试获取锁
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    /**
     * 非阻塞方式获取锁
     * @param key key
     * @param expireTime 指定持有时间
     */
    public Boolean tryLock(String key,Integer expireTime){
        try {
            RLock lock = redissonClient.getLock(LOCK_PREFIX + key);

            //非阻塞方式获取锁,设置在指定时间内失败重试获取锁
            return lock.tryLock(5L,expireTime,TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            return false;
        }
    }

    /**
     * 释放锁
     * @param key
     */
    public void unlock(String key) {
        RLock lock = redissonClient.getLock(LOCK_PREFIX+key);
        if (lock.isLocked()) {
            lock.unlock();
        }
    }
}
相关推荐
2401_8576100321 分钟前
Spring Boot框架:电商系统的技术优势
java·spring boot·后端
希忘auto37 分钟前
详解MySQL安装
java·mysql
冰淇淋烤布蕾1 小时前
EasyExcel使用
java·开发语言·excel
拾荒的小海螺1 小时前
JAVA:探索 EasyExcel 的技术指南
java·开发语言
sam-1231 小时前
k8s上部署redis高可用集群
redis·docker·k8s
Jakarta EE1 小时前
正确使用primefaces的process和update
java·primefaces·jakarta ee
马剑威(威哥爱编程)1 小时前
哇喔!20种单例模式的实现与变异总结
java·开发语言·单例模式
看山还是山,看水还是。1 小时前
Redis 配置
运维·数据库·redis·安全·缓存·测试覆盖率
谷新龙0011 小时前
Redis运行时的10大重要指标
数据库·redis·缓存
java—大象2 小时前
基于java+springboot+layui的流浪动物交流信息平台设计实现
java·开发语言·spring boot·layui·课程设计