開發/測試環境常將 Redis 部署在 VMware 虛擬機內,宿主機或外部 Java 應用需跨網絡訪問。本文系統講解 VMware 三種網絡模式選擇、端口映射配置、防火牆策略、Jedis/Lettuce 客戶端配置優化、常見連接故障排查與生產級最佳實踐。
| 模式 | 適用場景 | IP 特徵 | 外部訪問 |
|---|---|---|---|
| 橋接模式 | 開發/測試,需虛擬機像物理機同網段 | 獲取路由器 DHCP IP,與宿主機同網段 | 直接訪問 VM IP,無需映射 |
| NAT 模式 | 隔離環境、筆記本開發、多 VM 內部通信 | VMware 虛擬 DHCP 分配 (如 192.168.x.x) | 需配置端口轉發 (VMnet8) |
| 僅主機模式 | 完全隔離測試、安全合規環境 | VMware 虛擬 DHCP (如 192.168.y.y) | 僅宿主機可訪問,外部不可達 |
推薦:開發機首選橋接模式(最簡單);筆記本/無線網絡不穩定時用NAT + 端口映射。
# 虛擬機內執行
ip addr show ens33 # 或 ifconfig
# 假設獲取 192.168.100.128
6379(或自定義如 16379 避免衝突)192.168.100.1286379# redis.conf 關鍵配置
bind 0.0.0.0 # 監聽所有介面,或具體內網 IP
port 6379
protected-mode no # 關閉保護模式(無密碼時必須),生產請設密碼 + ACL
# requirepass your_strong_password # 生產必開
# 關閉防火牆或放行端口 (CentOS/RHEL)
firewall-cmd --permanent --add-port=6379/tcp
firewall-cmd --reload
# Ubuntu
ufw allow 6379/tcp
@Bean
public JedisPool jedisPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(50); // 最大連接數
config.setMaxIdle(20); // 最大空閒
config.setMinIdle(5); // 最小空閒
config.setTestOnBorrow(true); // 借用時檢測
config.setTestOnReturn(true); // 歸還時檢測
config.setTestWhileIdle(true); // 空閒檢測
config.setMinEvictableIdleTimeMillis(30000);
config.setTimeBetweenEvictionRunsMillis(60000);
// NAT 映射場景:宿主機 IP + 映射端口
return new JedisPool(config, "192.168.1.100", 16379, 3000, "password", 0);
}
@Bean
public RedisClient redisClient() {
RedisClient client = RedisClient.create(
RedisURI.Builder.redis("192.168.1.100", 16379)
.withPassword("password")
.withTimeout(Duration.ofSeconds(3))
.build());
// 連接池
GenericObjectPoolConfig<StatefulRedisConnection<String, String>> poolConfig = new GenericObjectPoolConfig<>();
poolConfig.setMaxTotal(50);
return client;
}
@Bean
public StatefulRedisConnection<String, String> connection(RedisClient client) {
return client.connect(); // 或 client.connectPubSub()
}
spring:
redis:
host: 192.168.1.100 # 宿主機 IP 或虛擬機 IP (橋接模式)
port: 16379 # 映射端口
password: your_password
timeout: 3000ms
lettuce:
pool:
max-active: 50
max-idle: 20
min-idle: 5
shutdown-timeout: 100ms
| 現象 | 可能原因 | 排查步驟 |
|---|---|---|
| Connection refused | 端口映射未生效/防火牆攔截/Redis 未綁定 0.0.0.0 | 1. 宿主機 telnet localhost 16379 2. 虛擬機 netstat -anpt | grep 6379 3. 檢查 VMnet NAT 映射規則 4. 關閉防火牆測試 |
| Connection timed out | 網絡不可達/路由錯誤/防火牆默認拒絕 | 1. ping 虛擬機IP 2. traceroute 3. 檢查宿主機/虛擬機防火牆 4. 橋接模式檢查網卡綁定 |
| Authentication failed | 密碼錯誤/ACL 限制/protected-mode 未關 | 1. redis-cli -a password ping 2. 檢查 requirepass 3. 臨時 CONFIG SET protected-mode no |
| JedisConnectionException: Could not get a resource from the pool | 連接池耗盡/閒置連接被服務端斷開/網絡抖動 | 1. 增大 maxTotal 2. 啟用 testOnBorrow/testWhileIdle 3. 設置合理 idle 超時驅逐 4. 檢查 Redis timeout 設置 |
| MOVED/ASK 錯誤 (集群模式) | 客戶端非集群模式連接集群節點 | 使用 JedisCluster 或 RedisClusterClient,而非單機客戶端 |
VMware 內網 Redis 連接核心在於:選對網絡模式(橋接最簡、NAT 需映射)、Redis 綁定 0.0.0.0 關閉保護模式、防火牆放行端口、客戶端配置連接池與超時重試。開發環境用 NAT 映射靈活;生產環境堅持私有網絡直連,杜絕端口映射暴露。掌握排查清單,連接問題分鐘級定位。