粉粉蕉的笔记本粉粉蕉的笔记本
  • JAVA

    • 代码笔记
    • Java8实战
    • 分布式事务实战(Seata)
    • 模板引擎(FreeMarker)
    • SpringSecurity
    • Maven
  • PYTHON

    • 概述
    • python3
    • python3(菜鸟教程)
    • pandas
    • numpy
    • matplotlib
  • 中间件

    • Kafka
    • RocketMQ
    • Redis
    • MongoDB
    • Elastic Search
  • 数据库

    • Mysql
  • 设计模式
  • 运维

    • linux命令速查
    • windows命令速查
    • Docker笔记
    • kubernetes学习笔记
    • kubernetes实操笔记
    • 运维工具大全
    • git操作宝典
  • 大数据

    • 概览
    • Hadoop
    • Hive
  • 机器学习

    • 机器学习概览
  • 概率论
  • 线性代数
  • 统计学
  • 金融知识学习
  • 聚宽
  • 因子分析
  • RSS
  • 资源导航
  • 医保
  • 健身

    • 笔记
    • 训练计划
  • 装修攻略
  • 读书笔记

    • 《深度学习》
我也想搭建这样的博客!
🚋开往
  • JAVA

    • 代码笔记
    • Java8实战
    • 分布式事务实战(Seata)
    • 模板引擎(FreeMarker)
    • SpringSecurity
    • Maven
  • PYTHON

    • 概述
    • python3
    • python3(菜鸟教程)
    • pandas
    • numpy
    • matplotlib
  • 中间件

    • Kafka
    • RocketMQ
    • Redis
    • MongoDB
    • Elastic Search
  • 数据库

    • Mysql
  • 设计模式
  • 运维

    • linux命令速查
    • windows命令速查
    • Docker笔记
    • kubernetes学习笔记
    • kubernetes实操笔记
    • 运维工具大全
    • git操作宝典
  • 大数据

    • 概览
    • Hadoop
    • Hive
  • 机器学习

    • 机器学习概览
  • 概率论
  • 线性代数
  • 统计学
  • 金融知识学习
  • 聚宽
  • 因子分析
  • RSS
  • 资源导航
  • 医保
  • 健身

    • 笔记
    • 训练计划
  • 装修攻略
  • 读书笔记

    • 《深度学习》
我也想搭建这样的博客!
🚋开往
    • 概述
    • 安装&项目结构
    • API
    • 数据结构
    • 使用场景
    • SpringBoot集成

Java项目集成Redis

1. 添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. 连接配置

spring:
  redis:
    host: localhost  # Redis服务器地址
    port: 6379       # Redis端口
    password:        # Redis密码(如无密码可省略)
    database: 0      # 数据库索引(默认为0)
    timeout: 2000ms  # 连接超时时间
    lettuce:
      pool:
        max-active: 8  # 连接池最大连接数
        max-idle: 8    # 连接池最大空闲连接数
        min-idle: 2    # 连接池最小空闲连接数

3. RedisTemplate配置

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.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        
        // Key使用String序列化
        template.setKeySerializer(new StringRedisSerializer());
        // Value使用JSON序列化
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        // Hash类型Key和Value序列化
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        
        template.afterPropertiesSet();
        return template;
    }
}

4. 使用RedisTemplate操作Redis

@Service
public class RedisService {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // 字符串操作(也可以存Object,但Object需要可序列化)
    public void setString(String key, Object value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public Object getString(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    // Hash表操作(对应Redis_API.md中的HASH命令)
    public void hset(String hashKey, String key, Object value) {
        redisTemplate.opsForHash().put(hashKey, key, value);
    }

    public Object hget(String hashKey, String key) {
        return redisTemplate.opsForHash().get(hashKey, key);
    }

    public Map<Object, Object> hgetAll(String hashKey) {
        return redisTemplate.opsForHash().entries(hashKey);
    }

    // 设置过期时间
    public void setExpire(String key, long timeout, TimeUnit unit) {
        redisTemplate.expire(key, timeout, unit);
    }
}

5. 分布式锁的实现

添加依赖

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.23.3</version>
</dependency>

获取锁

@Service
public class RedissonLockService {
    @Autowired
    private RedissonClient redissonClient;

    public void doBusiness() {
        RLock lock = redissonClient.getLock("distributed:lock");
        try {
            // 尝试获取锁,最多等待10秒,10秒后自动释放
            boolean locked = lock.tryLock(10, 10, TimeUnit.SECONDS);
            if (locked) {
                // 业务逻辑
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        } finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock(); // 释放锁
            }
        }
    }
}
Last Updated: 1/21/26, 6:25 AM
Contributors: dongyz8
Prev
使用场景