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

简介: 本文介绍了基于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


相关文章
|
4月前
|
存储 人工智能 算法
从零掌握贪心算法Java版:LeetCode 10题实战解析(上)
在算法世界里,有一种思想如同生活中的"见好就收"——每次做出当前看来最优的选择,寄希望于通过局部最优达成全局最优。这种思想就是贪心算法,它以其简洁高效的特点,成为解决最优问题的利器。今天我们就来系统学习贪心算法的核心思想,并通过10道LeetCode经典题目实战演练,带你掌握这种"步步为营"的解题思维。
|
4月前
|
存储 安全 Java
《数据之美》:Java集合框架全景解析
Java集合框架是数据管理的核心工具,涵盖List、Set、Map等体系,提供丰富接口与实现类,支持高效的数据操作与算法处理。
|
4月前
|
安全 Java 开发者
告别NullPointerException:Java Optional实战指南
告别NullPointerException:Java Optional实战指南
304 119
|
4月前
|
存储 缓存 NoSQL
Redis常见面试题全解析
Redis面试高频考点全解析:从过期删除、内存淘汰策略,到缓存雪崩、击穿、穿透及BigKey问题,深入原理与实战解决方案,助你轻松应对技术挑战,提升系统性能与稳定性。(238字)
|
5月前
|
人工智能 Java API
Java AI智能体实战:使用LangChain4j构建能使用工具的AI助手
随着AI技术的发展,AI智能体(Agent)能够通过使用工具来执行复杂任务,从而大幅扩展其能力边界。本文介绍如何在Java中使用LangChain4j框架构建一个能够使用外部工具的AI智能体。我们将通过一个具体示例——一个能获取天气信息和执行数学计算的AI助手,详细讲解如何定义工具、创建智能体并处理执行流程。本文包含完整的代码示例和架构说明,帮助Java开发者快速上手AI智能体的开发。
1826 8
|
5月前
|
Java 开发者
Java 函数式编程全解析:静态方法引用、实例方法引用、特定类型方法引用与构造器引用实战教程
本文介绍Java 8函数式编程中的四种方法引用:静态、实例、特定类型及构造器引用,通过简洁示例演示其用法,帮助开发者提升代码可读性与简洁性。
|
5月前
|
存储 监控 NoSQL
Redis高可用架构全解析:从主从复制到集群方案
Redis高可用确保服务持续稳定,避免单点故障导致数据丢失或业务中断。通过主从复制实现数据冗余,哨兵模式支持自动故障转移,Cluster集群则提供分布式数据分片与水平扩展,三者层层递进,保障读写分离、容灾切换与大规模数据存储,构建高性能、高可靠的Redis架构体系。
|
5月前
|
存储 缓存 NoSQL
Redis持久化深度解析:数据安全与性能的平衡艺术
Redis持久化解决内存数据易失问题,提供RDB快照与AOF日志两种机制。RDB恢复快、性能高,但可能丢数据;AOF安全性高,最多丢1秒数据,支持多种写回策略,适合不同场景。Redis 4.0+支持混合持久化,兼顾速度与安全。根据业务需求选择合适方案,实现数据可靠与性能平衡。(238字)
|
5月前
|
人工智能 Java API
Java与大模型集成实战:构建智能Java应用的新范式
随着大型语言模型(LLM)的API化,将其强大的自然语言处理能力集成到现有Java应用中已成为提升应用智能水平的关键路径。本文旨在为Java开发者提供一份实用的集成指南。我们将深入探讨如何使用Spring Boot 3框架,通过HTTP客户端与OpenAI GPT(或兼容API)进行高效、安全的交互。内容涵盖项目依赖配置、异步非阻塞的API调用、请求与响应的结构化处理、异常管理以及一些面向生产环境的最佳实践,并附带完整的代码示例,助您快速将AI能力融入Java生态。
842 12
|
5月前
|
Java 开发者
Java并发编程:CountDownLatch实战解析
Java并发编程:CountDownLatch实战解析
507 100