Redis 实操要点:Java 最新技术栈的实战解析

本文涉及的产品
应用实时监控服务-可观测链路OpenTelemetry版,每月50GB免费额度
云原生网关 MSE Higress,422元/月
注册配置 MSE Nacos/ZooKeeper,118元/月
简介: 本文介绍了基于Spring Boot 3、Redis 7和Lettuce客户端的Redis高级应用实践。内容包括:1)现代Java项目集成Redis的配置方法;2)使用Redisson实现分布式可重入锁与公平锁;3)缓存模式解决方案,包括布隆过滤器防穿透和随机过期时间防雪崩;4)Redis数据结构的高级应用,如HyperLogLog统计UV和GeoHash处理地理位置。文章提供了详细的代码示例,涵盖Redis在分布式系统中的核心应用场景,特别适合需要处理高并发、分布式锁等问题的开发场景。

以下是基于最新技术栈的Redis实操内容,结合Spring Boot 3、Redis 7及Lettuce客户端,覆盖分布式锁、缓存模式、集群配置等核心场景。

一、现代Java项目集成Redis

1. Spring Boot 3 + Redis 7 配置

pom.xml中添加依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Redisson 分布式锁实现 -->
<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson-spring-boot-starter</artifactId>
    <version>3.23.1</version>
</dependency>

application.yml配置:

spring:
  redis:
    host: localhost
    port: 6379
    password: your_password  # 生产环境建议使用安全凭证
    client-type: lettuce      # 默认使用Lettuce客户端
    timeout: 5000ms
    # 连接池配置
    lettuce:
      pool:
        max-active: 100
        max-wait: -1ms
        max-idle: 10
        min-idle: 0
    # Redis集群配置示例
    cluster:
      nodes:
        - 192.168.1.1:6379
        - 192.168.1.2:6379
        - 192.168.1.3:6379

二、分布式锁最佳实践(Redisson)

1. 可重入锁实现

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class DistributedLockService {
   
    private final RedissonClient redissonClient;

    public DistributedLockService(RedissonClient redissonClient) {
   
        this.redissonClient = redissonClient;
    }

    // 阻塞锁示例
    public void doWithLock(String lockName, Runnable action) {
   
        RLock lock = redissonClient.getLock(lockName);
        try {
   
            // 尝试获取锁,等待10秒,自动释放时间30秒
            boolean isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS);
            if (isLocked) {
   
                action.run();
            }
        } catch (InterruptedException e) {
   
            Thread.currentThread().interrupt();
        } finally {
   
            if (lock.isHeldByCurrentThread()) {
   
                lock.unlock();
            }
        }
    }

    // 公平锁示例
    public void doWithFairLock(String lockName, Runnable action) {
   
        RLock fairLock = redissonClient.getFairLock(lockName);
        try {
   
            fairLock.lock();
            action.run();
        } finally {
   
            if (fairLock.isHeldByCurrentThread()) {
   
                fairLock.unlock();
            }
        }
    }
}

2. 业务场景应用

@Service
public class OrderService {
   
    @Autowired
    private DistributedLockService lockService;

    public void createOrder(String orderId) {
   
        lockService.doWithLock("order:" + orderId, () -> {
   
            // 检查库存、生成订单等业务逻辑
            log.info("订单创建中: {}", orderId);
        });
    }
}

三、缓存模式实战

1. 缓存穿透防护(Bloom Filter)

import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

@Service
public class BloomFilterService {
   
    private final RBloomFilter<String> bloomFilter;

    public BloomFilterService(RedissonClient redissonClient) {
   
        // 初始化布隆过滤器,预计元素100万,误判率0.01%
        bloomFilter = redissonClient.getBloomFilter("userBloomFilter");
        bloomFilter.tryInit(1000000, 0.0001);
    }

    public void addToBloomFilter(String key) {
   
        bloomFilter.add(key);
    }

    public boolean mightContain(String key) {
   
        return bloomFilter.contains(key);
    }
}

2. 缓存雪崩预防

@Service
public class ProductService {
   
    @Autowired
    private RedisTemplate<String, Product> redisTemplate;
    @Value("${cache.expire.random.min:60}")
    private int minExpire;
    @Value("${cache.expire.random.max:120}")
    private int maxExpire;

    public Product getProduct(Long id) {
   
        String key = "product:" + id;
        Product product = redisTemplate.opsForValue().get(key);

        if (product == null) {
   
            // 从数据库加载
            product = loadFromDatabase(id);

            // 设置随机过期时间(60-120秒)
            long expire = minExpire + ThreadLocalRandom.current().nextLong(maxExpire - minExpire);
            redisTemplate.opsForValue().set(key, product, expire, TimeUnit.SECONDS);
        }
        return product;
    }
}

四、Redis数据结构高级应用

1. HyperLogLog统计UV

@Service
public class AnalyticsService {
   
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void logVisit(String userId, String pageId) {
   
        String key = "uv:" + pageId + ":daily";
        redisTemplate.opsForHyperLogLog().add(key, userId);
    }

    public long getDailyUV(String pageId) {
   
        String key = "uv:" + pageId + ":daily";
        return redisTemplate.opsForHyperLogLog().size(key);
    }
}

2. GeoHash地理位置查询

@Service
public class LocationService {
   
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final String KEY = "shop_locations";

    public void addShopLocation(String shopId, double longitude, double latitude) {
   
        redisTemplate.opsForGeo().add(KEY, new Point(longitude, latitude), shopId);
    }

    public List<String> findNearbyShops(double longitude, double latitude, double radius, String unit) {
   
        Circle circle = new Circle(new Point(longitude, latitude), new Distance(radius, RedisGeoCommands.DistanceUnit.valueOf(unit)));
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = 
            redisTemplate.opsForGeo().radius(KEY, circle);

        return results.getContent().stream()
                .map(result -> result.getContent().getName())
                .collect(Collectors.toList());
    }
}

五、Redis集群与哨兵模式配置

1. 集群模式配置

@Configuration
public class RedisClusterConfig {
   
    @Bean
    public RedisConnectionFactory redisConnectionFactory(RedisProperties properties) {
   
        RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration(properties.getCluster().getNodes());
        clusterConfig.setPassword(RedisPassword.of(properties.getPassword()));

        // 开启SSL(生产环境建议配置)
        if (properties.isSsl()) {
   
            SslSocketFactory sslSocketFactory = (SslSocketFactory) SslSocketFactory.getDefault();
            LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder()
                    .useSsl().sslSocketFactory(sslSocketFactory).build();
            return new LettuceConnectionFactory(clusterConfig, clientConfig);
        }

        return new LettuceConnectionFactory(clusterConfig);
    }
}

2. 哨兵模式配置

spring:
  redis:
    sentinel:
      master: mymaster
      nodes:
        - 192.168.1.10:26379
        - 192.168.1.11:26379
        - 192.168.1.12:26379
    password: your_sentinel_password

六、性能监控与调优

1. 自定义Redis监控指标

@Configuration
public class RedisMetricsConfig {
   
    @Bean
    public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags(RedisProperties properties) {
   
        return registry -> registry.config().commonTags(
                "redis.host", properties.getHost(),
                "redis.port", String.valueOf(properties.getPort())
        );
    }

    @Bean
    public RedisHealthIndicator redisHealthIndicator(RedisConnectionFactory connectionFactory) {
   
        return new RedisHealthIndicator(connectionFactory);
    }
}

2. Redis慢查询日志分析

@Service
public class RedisSlowLogService {
   
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public List<SlowLogEntry> getSlowLog(int count) {
   
        return redisTemplate.execute((RedisCallback<List<SlowLogEntry>>) connection -> {
   
            List<org.springframework.data.redis.connection.RedisServerCommands.SlowLogEntry> entries = 
                connection.serverCommands().slowLogGet(count);

            return entries.stream()
                    .map(entry -> new SlowLogEntry(
                            entry.getId(), 
                            entry.getExecutionTime(), 
                            entry.getTimestamp(), 
                            entry.getArgs()))
                    .collect(Collectors.toList());
        });
    }
}

// 自定义SlowLogEntry类
public class SlowLogEntry {
   
    private final long id;
    private final long executionTime;
    private final Date timestamp;
    private final List<byte[]> args;

    // 构造函数、Getter略
}

七、高可用架构实践

1. Redis Sentinel自动故障转移

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

    public void checkSentinelStatus() {
   
        RNodesGroup nodesGroup = redissonClient.getNodesGroup();
        List<Node> nodes = nodesGroup.getNodes();

        nodes.forEach(node -> {
   
            System.out.println("节点状态: " + node.getAddr() + " - " + node.getStatus());
        });
    }
}

2. Redis Cluster分片策略

@Service
public class ShardingService {
   
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 使用哈希标签确保多个Key在同一节点
    public void batchOperations() {
   
        String key1 = "{user:1}:profile";
        String key2 = "{user:1}:orders";

        redisTemplate.opsForValue().set(key1, "profile_data");
        redisTemplate.opsForList().rightPush(key2, "order1", "order2");

        // 使用MGET保证原子性(同一节点)
        List<String> values = redisTemplate.opsForValue().multiGet(Arrays.asList(key1, key2));
    }
}

八、安全加固方案

1. Redis ACL配置

@Configuration
public class RedisSecurityConfig {
   
    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
   
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName("localhost");
        config.setPort(6379);

        // 使用ACL认证
        RedisPassword password = RedisPassword.of("user:password");
        config.setPassword(password);

        return new LettuceConnectionFactory(config);
    }
}

2. 数据加密传输

spring:
  redis:
    host: redis.example.com
    port: 6379
    ssl: true
    timeout: 5000
    password: ${
   REDIS_PASSWORD}
    lettuce:
      pool:
        max-active: 8

九、异步操作与响应式编程

1. Reactive Redis操作

@Service
public class ReactiveUserService {
   
    private final ReactiveRedisTemplate<String, User> reactiveRedisTemplate;

    public ReactiveUserService(ReactiveRedisTemplate<String, User> reactiveRedisTemplate) {
   
        this.reactiveRedisTemplate = reactiveRedisTemplate;
    }

    public Mono<User> getUser(String id) {
   
        return reactiveRedisTemplate.opsForValue().get("user:" + id);
    }

    public Mono<Void> saveUser(User user) {
   
        return reactiveRedisTemplate.opsForValue()
                .set("user:" + user.getId(), user)
                .then();
    }
}

十、性能压测与优化

1. Lettuce连接池优化

spring:
  redis:
    lettuce:
      pool:
        max-active: 200  # 最大连接数
        max-wait: -1ms   # 获取连接的最大等待时间
        max-idle: 50     # 最大空闲连接数
        min-idle: 10     # 最小空闲连接数
      shutdown-timeout: 100ms  # 关闭超时时间

2. Pipeline批量操作

@Service
public class BatchOperationService {
   
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void batchSet(Map<String, String> data) {
   
        redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
   
            data.forEach((key, value) -> {
   
                connection.set(key.getBytes(), value.getBytes());
            });
            return null;
        });
    }
}

总结

以上代码覆盖了Redis在现代Java项目中的核心应用场景,包括:

  1. 最新技术集成:Spring Boot 3、Redisson 3.23、Lettuce客户端
  2. 分布式锁最佳实践:可重入锁、公平锁、自动续期
  3. 缓存模式优化:布隆过滤器防穿透、随机过期防雪崩
  4. 高级数据结构应用:HyperLogLog统计、GeoHash地理位置查询
  5. 高可用架构:集群、哨兵模式配置与监控
  6. 性能与安全:连接池优化、SSL加密、ACL认证

这些示例代码可直接用于生产环境,建议根据实际业务需求进行参数调优和功能扩展。

--
Redis,

--


代码获取方式
https://pan.quark.cn/s/14fcf913bae6


相关文章
|
5天前
|
人工智能 Cloud Native Java
2025 年 Java 应届生斩获高薪需掌握的技术实操指南与实战要点解析
本指南为2025年Java应届生打造,涵盖JVM调优、响应式编程、云原生、微服务、实时计算与AI部署等前沿技术,结合电商、数据处理等真实场景,提供可落地的技术实操方案,助力掌握高薪开发技能。
42 2
|
5天前
|
缓存 Java API
Java 面试实操指南与最新技术结合的实战攻略
本指南涵盖Java 17+新特性、Spring Boot 3微服务、响应式编程、容器化部署与数据缓存实操,结合代码案例解析高频面试技术点,助你掌握最新Java技术栈,提升实战能力,轻松应对Java中高级岗位面试。
31 0
|
2天前
|
存储 安全 算法
Java 核心知识与技术全景解析
本文涵盖 Java 多方面核心知识,包括基础语法中重载与重写、== 与 equals 的区别,String 等类的特性及异常体系;集合类中常见数据结构、各集合实现类的特点,以及 HashMap 的底层结构和扩容机制;网络编程中 BIO、NIO、AIO 的差异;IO 流的分类及用途。 线程与并发部分详解了 ThreadLocal、悲观锁与乐观锁、synchronized 的原理及锁升级、线程池核心参数;JVM 部分涉及堆内存结构、垃圾回收算法及伊甸园等区域的细节;还包括 Lambda 表达式、反射与泛型的概念,以及 Tomcat 的优化配置。内容全面覆盖 Java 开发中的关键技术点,适用于深
|
2天前
|
缓存 安全 前端开发
Java 核心知识点与实战应用解析
我梳理的这些内容涵盖了 Java 众多核心知识点。包括 final 关键字的作用(修饰类、方法、变量的特性);重载与重写的区别;反射机制的定义、优缺点及项目中的应用(如结合自定义注解处理数据、框架底层实现)。 还涉及 String、StringBuffer、StringBuilder 的差异;常见集合类及线程安全类,ArrayList 与 LinkedList 的区别;HashMap 的实现原理、put 流程、扩容机制,以及 ConcurrentHashMap 的底层实现。 线程相关知识中,创建线程的四种方式,Runnable 与 Callable 的区别,加锁方式(synchronize
|
2天前
|
存储 Java 程序员
Java 基础知识点全面梳理包含核心要点及难点解析 Java 基础知识点
本文档系统梳理了Java基础知识点,涵盖核心特性、语法基础、面向对象编程、数组字符串、集合框架、异常处理及应用实例,帮助初学者全面掌握Java入门知识,提升编程实践能力。附示例代码下载链接。
11 0
|
3天前
|
IDE Java API
Java 17 新特性与微服务开发的实操指南
本内容涵盖Java 11至Java 17最新特性实战,包括var关键字、字符串增强、模块化系统、Stream API、异步编程、密封类等,并提供图书管理系统实战项目,帮助开发者掌握现代Java开发技巧与工具。
16 0
|
3天前
|
存储 安全 Java
从基础语法到实战应用的 Java 入门必备知识全解析
本文介绍了Java入门必备知识,涵盖开发环境搭建、基础语法、面向对象编程、集合框架、异常处理、多线程和IO流等内容,结合实例帮助新手快速掌握Java核心概念与应用技巧。
17 0
|
2月前
|
缓存 NoSQL 关系型数据库
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
美团面试:MySQL有1000w数据,redis只存20w的数据,如何做 缓存 设计?
|
2月前
|
缓存 NoSQL Java
Redis+Caffeine构建高性能二级缓存
大家好,我是摘星。今天为大家带来的是Redis+Caffeine构建高性能二级缓存,废话不多说直接开始~
372 0
|
2月前
|
消息中间件 缓存 NoSQL
基于Spring Data Redis与RabbitMQ实现字符串缓存和计数功能(数据同步)
总的来说,借助Spring Data Redis和RabbitMQ,我们可以轻松实现字符串缓存和计数的功能。而关键的部分不过是一些"厨房的套路",一旦你掌握了这些套路,那么你就像厨师一样可以准备出一道道饕餮美食了。通过这种方式促进数据处理效率无疑将大大提高我们的生产力。
126 32