1. JDBC — 基础连接(类似 mysql2)
<!-- pom.xml -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>
大约 4 分钟
<!-- pom.xml -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>
npm install mysql2
const mysql = require('mysql2/promise'); // 使用 Promise 版本(推荐)
// 连接配置(类似前端请求的 baseURL + 鉴权)
const pool = mysql.createPool({
host: 'localhost', // 数据库主机
port: 3306, // MySQL 默认端口
user: 'root', // 用户名
password: '123456', // 密码
database: 'my_app', // 数据库名
waitForConnections: true,
connectionLimit: 10, // 连接池大小
queueLimit: 0,
});
// 测试连接
async function testConnection() {
try {
const connection = await pool.getConnection();
console.log('数据库连接成功 ✅');
connection.release();
} catch (err) {
console.error('数据库连接失败 ❌', err);
}
}
| 客户端 | 特点 | 类似前端 |
|---|---|---|
| Jedis | 轻量,直连 Redis(非线程安全需连接池) | ioredis 基础用法 |
| Lettuce | 异步+同步,线程安全,基于 Netty | ioredis 高级用法 |
| Spring Data Redis | Spring Boot 整合,封装度高 | ORM 封装层 |
npm install ioredis
const Redis = require('ioredis');
// 连接 Redis(默认 localhost:6379)
const redis = new Redis();
// 指定配置
const redis = new Redis({
host: 'localhost',
port: 6379,
password: '123456',
db: 0, // 数据库编号(默认 0~15)
retryStrategy: (times) => {
// 断线重连策略
return Math.min(times * 50, 2000); // 最多等 2 秒
},
});
// 连接字符串方式
const redis = new Redis('redis://:password@localhost:6379/0');
// 测试连接
redis.ping().then(res => {
console.log('Redis 连接', res === 'PONG' ? '✅' : '❌');
});