java程序连接Redis









RedisOperation:
package com.hadoop.experiment7;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Redis数据库操作类
* 完成实验4的Redis部分
*/
public class RedisOperation {
// Redis服务器配置(根据你的虚拟机IP)
private static final String REDIS_HOST = "192.168.249.129";
private static final int REDIS_PORT = 6379;
private static final int REDIS_TIMEOUT = 5000;
// Jedis连接池
private static JedisPool jedisPool = null;
/**
* 初始化Redis连接池
*/
static {
try {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(10); // 最大连接数
poolConfig.setMaxIdle(5); // 最大空闲连接数
poolConfig.setMinIdle(1); // 最小空闲连接数
poolConfig.setMaxWaitMillis(3000); // 最大等待时间
// 创建连接池
jedisPool = new JedisPool(poolConfig, REDIS_HOST, REDIS_PORT, REDIS_TIMEOUT);
System.out.println("✓ Redis连接池初始化成功");
// 测试连接
try (Jedis jedis = jedisPool.getResource()) {
String pong = jedis.ping();
System.out.println("✓ Redis连接测试: " + pong);
}
} catch (Exception e) {
System.err.println("✗ Redis连接池初始化失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 获取Jedis连接
*/
public static Jedis getJedis() {
if (jedisPool == null) {
throw new RuntimeException("Redis连接池未初始化");
}
return jedisPool.getResource();
}
/**
* 关闭连接池
*/
public static void close() {
if (jedisPool != null) {
jedisPool.close();
System.out.println("✓ Redis连接池已关闭");
}
}
/**
* 工具方法:打印分隔线
*/
private static void printSeparator(String title) {
System.out.println("\n" + repeatString("=", 60));
System.out.println(title);
System.out.println(repeatString("=", 60));
}
private static void printSubSeparator(String title) {
System.out.println("\n" + repeatString("-", 40));
System.out.println(title);
System.out.println(repeatString("-", 40));
}
/**
* 重复字符串(兼容Java 1.8)
*/
private static String repeatString(String str, int count) {
if (count <= 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(str);
}
return sb.toString();
}
/**
* 1. 用哈希结构设计学生表Student
* 使用student:zhangsan和student:lisi作为键
*/
public static void createStudentData() {
printSeparator("1. 创建学生数据(哈希结构)");
try (Jedis jedis = getJedis()) {
// 删除旧数据(如果存在)
jedis.del("student:zhangsan", "student:lisi");
// 创建zhangsan的数据
Map<String, String> zhangsanData = new HashMap<>();
zhangsanData.put("English", "69");
zhangsanData.put("Math", "86");
zhangsanData.put("Computer", "77");
jedis.hset("student:zhangsan", zhangsanData);
System.out.println("✓ 创建zhangsan数据: " + zhangsanData);
// 创建lisi的数据
Map<String, String> lisiData = new HashMap<>();
lisiData.put("English", "55");
lisiData.put("Math", "100");
lisiData.put("Computer", "88");
jedis.hset("student:lisi", lisiData);
System.out.println("✓ 创建lisi数据: " + lisiData);
// 验证创建结果
long count = jedis.hlen("student:zhangsan");
System.out.println("✓ zhangsan字段数: " + count);
} catch (Exception e) {
System.err.println("创建学生数据失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 2. 用hgetall命令输出学生成绩信息
*/
public static void getAllStudentScores() {
printSeparator("2. 输出所有学生成绩信息");
try (Jedis jedis = getJedis()) {
// 获取所有student键
Set<String> studentKeys = jedis.keys("student:*");
if (studentKeys.isEmpty()) {
System.out.println("没有找到学生数据");
return;
}
System.out.println("找到 " + studentKeys.size() + " 个学生:");
for (String key : studentKeys) {
printSubSeparator("学生: " + key);
// 使用hgetall获取所有字段
Map<String, String> scores = jedis.hgetAll(key);
if (scores.isEmpty()) {
System.out.println("该学生没有成绩数据");
} else {
System.out.println("科目\t\t成绩");
System.out.println(repeatString("-", 20));
for (Map.Entry<String, String> entry : scores.entrySet()) {
System.out.printf("%-10s\t%s\n", entry.getKey(), entry.getValue());
}
// 计算总分和平均分
calculateStudentStats(scores, key);
}
}
} catch (Exception e) {
System.err.println("获取学生成绩失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 计算学生统计信息
*/
private static void calculateStudentStats(Map<String, String> scores, String studentKey) {
try {
int total = 0;
int count = 0;
for (String scoreStr : scores.values()) {
int score = Integer.parseInt(scoreStr);
total += score;
count++;
}
if (count > 0) {
double average = (double) total / count;
System.out.println(repeatString("-", 20));
System.out.printf("总分: %d, 平均分: %.2f\n", total, average);
// 判断成绩等级
String grade = getOverallGrade(average);
System.out.println("总体等级: " + grade);
}
} catch (NumberFormatException e) {
System.out.println("成绩数据格式错误,无法计算统计信息");
}
}
/**
* 获取总体成绩等级
*/
private static String getOverallGrade(double average) {
if (average >= 90) return "优秀";
else if (average >= 80) return "良好";
else if (average >= 70) return "中等";
else if (average >= 60) return "及格";
else return "不及格";
}
/**
* 3. 查询zhangsan的Computer成绩
*/
public static void queryZhangsanComputerScore() {
printSeparator("3. 查询zhangsan的Computer成绩");
try (Jedis jedis = getJedis()) {
String score = jedis.hget("student:zhangsan", "Computer");
if (score != null) {
System.out.println("学生: zhangsan");
System.out.println("科目: Computer");
System.out.println("成绩: " + score);
// 显示等级
int scoreInt = Integer.parseInt(score);
String grade = getGrade(scoreInt);
System.out.println("等级: " + grade);
} else {
System.out.println("未找到zhangsan的Computer成绩");
}
} catch (Exception e) {
System.err.println("查询失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 根据单科分数获取等级
*/
private static String getGrade(int score) {
if (score >= 90) return "优秀";
else if (score >= 80) return "良好";
else if (score >= 70) return "中等";
else if (score >= 60) return "及格";
else return "不及格";
}
/**
* 4. 修改lisi的Math成绩,改为95
*/
public static void updateLisiMathScore() {
printSeparator("4. 修改lisi的Math成绩,改为95");
try (Jedis jedis = getJedis()) {
// 先获取旧值
String oldScore = jedis.hget("student:lisi", "Math");
if (oldScore != null) {
System.out.println("原成绩: " + oldScore);
} else {
System.out.println("原成绩: 不存在");
}
// 修改成绩
jedis.hset("student:lisi", "Math", "95");
System.out.println("新成绩: 95");
// 验证修改结果
String newScore = jedis.hget("student:lisi", "Math");
System.out.println("验证结果: " + newScore);
System.out.println("✓ 修改成功");
} catch (Exception e) {
System.err.println("修改失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 5. 添加scofield的数据
* 实验要求2(1): English:45 Math:89 Computer:100
*/
public static void addScofieldRecord() {
printSeparator("5. 添加scofield记录");
try (Jedis jedis = getJedis()) {
// 创建scofield的数据
Map<String, String> scofieldData = new HashMap<>();
scofieldData.put("English", "45");
scofieldData.put("Math", "89");
scofieldData.put("Computer", "100");
jedis.hset("student:scofield", scofieldData);
System.out.println("✓ 添加scofield记录成功");
System.out.println("数据内容:");
System.out.println(" English: 45");
System.out.println(" Math: 89");
System.out.println(" Computer: 100");
// 显示添加后的数据
Map<String, String> savedData = jedis.hgetAll("student:scofield");
System.out.println("\n验证保存的数据:");
for (Map.Entry<String, String> entry : savedData.entrySet()) {
System.out.println(" " + entry.getKey() + ": " + entry.getValue());
}
} catch (Exception e) {
System.err.println("添加记录失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 6. 获取scofield的English成绩信息
* 实验要求2(2)
*/
public static void getScofieldEnglishScore() {
printSeparator("6. 获取scofield的English成绩信息");
try (Jedis jedis = getJedis()) {
String score = jedis.hget("student:scofield", "English");
if (score != null) {
System.out.println("学生: scofield");
System.out.println("科目: English");
System.out.println("成绩: " + score);
// 显示等级
int scoreInt = Integer.parseInt(score);
String grade = getGrade(scoreInt);
System.out.println("等级: " + grade);
// 与其他学生比较
compareWithOtherStudents("English", scoreInt);
} else {
System.out.println("未找到scofield的English成绩");
}
} catch (Exception e) {
System.err.println("查询失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 与其他学生比较
*/
private static void compareWithOtherStudents(String subject, int targetScore) {
try (Jedis jedis = getJedis()) {
System.out.println("\n与其他学生比较:");
System.out.println("学生\t\t" + subject + "成绩\t等级");
System.out.println(repeatString("-", 30));
Set<String> studentKeys = jedis.keys("student:*");
for (String key : studentKeys) {
String studentName = key.substring(key.indexOf(":") + 1);
String scoreStr = jedis.hget(key, subject);
if (scoreStr != null) {
int score = Integer.parseInt(scoreStr);
String grade = getGrade(score);
System.out.printf("%-10s\t%d\t\t%s\n", studentName, score, grade);
}
}
} catch (Exception e) {
System.out.println("比较时发生错误: " + e.getMessage());
}
}
/**
* 7. 查询特定学生的所有成绩
*/
public static void queryStudentAllScores(String studentName) {
printSubSeparator("查询学生: " + studentName);
try (Jedis jedis = getJedis()) {
String key = "student:" + studentName;
Map<String, String> scores = jedis.hgetAll(key);
if (scores.isEmpty()) {
System.out.println("学生 " + studentName + " 不存在或没有成绩数据");
return;
}
System.out.println("学生: " + studentName);
System.out.println("科目\t\t成绩\t等级");
System.out.println(repeatString("-", 30));
int total = 0;
int count = 0;
for (Map.Entry<String, String> entry : scores.entrySet()) {
String subject = entry.getKey();
String scoreStr = entry.getValue();
int score = Integer.parseInt(scoreStr);
String grade = getGrade(score);
System.out.printf("%-10s\t%s\t\t%s\n", subject, scoreStr, grade);
total += score;
count++;
}
if (count > 0) {
double average = (double) total / count;
System.out.println(repeatString("-", 30));
System.out.printf("总分: %d, 平均分: %.2f\n", total, average);
System.out.println("总体等级: " + getOverallGrade(average));
}
} catch (Exception e) {
System.err.println("查询失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 8. 计算各科平均分(扩展功能)
*/
public static void calculateSubjectAverages() {
printSeparator("7. 计算各科平均分(扩展功能)");
try (Jedis jedis = getJedis()) {
Set<String> studentKeys = jedis.keys("student:*");
if (studentKeys.isEmpty()) {
System.out.println("没有学生数据");
return;
}
Map<String, Integer> subjectTotals = new HashMap<>();
Map<String, Integer> subjectCounts = new HashMap<>();
// 收集各科成绩
for (String key : studentKeys) {
Map<String, String> scores = jedis.hgetAll(key);
for (Map.Entry<String, String> entry : scores.entrySet()) {
String subject = entry.getKey();
String scoreStr = entry.getValue();
try {
int score = Integer.parseInt(scoreStr);
// 累加总分
subjectTotals.put(subject,
subjectTotals.getOrDefault(subject, 0) + score);
// 累加人数
subjectCounts.put(subject,
subjectCounts.getOrDefault(subject, 0) + 1);
} catch (NumberFormatException e) {
// 忽略非数字成绩
}
}
}
// 计算并显示平均分
System.out.println("科目\t\t平均分\t学生数");
System.out.println(repeatString("-", 30));
for (String subject : subjectTotals.keySet()) {
int total = subjectTotals.get(subject);
int count = subjectCounts.get(subject);
if (count > 0) {
double average = (double) total / count;
System.out.printf("%-10s\t%.2f\t%d\n", subject, average, count);
}
}
// 显示学生总数
System.out.println(repeatString("-", 30));
System.out.println("学生总数: " + studentKeys.size());
} catch (Exception e) {
System.err.println("计算平均分失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 9. 删除学生数据(清理)
*/
public static void cleanup() {
printSeparator("清理数据");
try (Jedis jedis = getJedis()) {
Set<String> studentKeys = jedis.keys("student:*");
if (!studentKeys.isEmpty()) {
long deleted = jedis.del(studentKeys.toArray(new String[0]));
System.out.println("✓ 清理完成,删除 " + deleted + " 个学生的数据");
} else {
System.out.println("没有需要清理的数据");
}
} catch (Exception e) {
System.err.println("清理失败: " + e.getMessage());
e.printStackTrace();
}
}
/**
* 10. 显示Redis信息
*/
public static void showRedisInfo() {
printSeparator("Redis服务器信息");
try (Jedis jedis = getJedis()) {
// 获取Redis信息
String info = jedis.info();
// 解析并显示关键信息
String[] lines = info.split("\n");
System.out.println("Redis信息:");
System.out.println(repeatString("-", 40));
for (String line : lines) {
if (line.startsWith("redis_version") ||
line.startsWith("uptime_in_days") ||
line.startsWith("connected_clients") ||
line.startsWith("used_memory_human") ||
line.startsWith("total_connections_received") ||
line.startsWith("total_commands_processed")) {
System.out.println(line);
}
}
// 显示数据库大小
long dbSize = jedis.dbSize();
System.out.println("数据库大小(key数量): " + dbSize);
} catch (Exception e) {
System.err.println("获取Redis信息失败: " + e.getMessage());
e.printStackTrace();
}
}
}
RedisExperimentDemo:
package com.hadoop.experiment7;
/**
* 实验4 Redis部分完整演示
*/
public class RedisExperimentDemo {
public static void main(String[] args) {
System.out.println("=== 实验4:NoSQL和关系数据库的操作比较 ===\n");
System.out.println("=== Redis数据库操作部分 ===\n");
try {
// ==================== 演示开始 ====================
System.out.println(repeatString("★", 60));
System.out.println(" Redis学生表操作演示");
System.out.println(repeatString("★", 60));
// 显示Redis信息
RedisOperation.showRedisInfo();
// 第一部分:Redis哈希结构设计
System.out.println("\n" + repeatString("=", 60));
System.out.println("第一部分:Redis哈希结构设计");
System.out.println(repeatString("=", 60));
System.out.println("\n1. 使用哈希结构存储学生数据");
System.out.println(repeatString("-", 40));
System.out.println("键格式: student:学生名");
System.out.println("字段: English, Math, Computer");
System.out.println("值: 成绩分数");
// 创建学生数据
System.out.println("\n2. 创建学生数据");
System.out.println(repeatString("-", 40));
RedisOperation.createStudentData();
// 第二部分:基本操作演示
System.out.println("\n" + repeatString("=", 60));
System.out.println("第二部分:基本操作演示");
System.out.println(repeatString("=", 60));
// 2.1 使用hgetall输出成绩
System.out.println("\n2.1 使用hgetall输出所有学生成绩");
System.out.println(repeatString("-", 40));
RedisOperation.getAllStudentScores();
// 2.2 使用hget查询特定成绩
System.out.println("\n2.2 使用hget查询zhangsan的Computer成绩");
System.out.println(repeatString("-", 40));
RedisOperation.queryZhangsanComputerScore();
// 2.3 修改成绩
System.out.println("\n2.3 修改lisi的Math成绩为95");
System.out.println(repeatString("-", 40));
RedisOperation.updateLisiMathScore();
// 查看修改后的结果
System.out.println("\n修改后的所有学生成绩:");
RedisOperation.getAllStudentScores();
// 第三部分:Java客户端编程
System.out.println("\n" + repeatString("=", 60));
System.out.println("第三部分:Java客户端编程(jedis)");
System.out.println(repeatString("=", 60));
// 3.1 添加scofield记录
System.out.println("\n3.1 添加scofield记录");
System.out.println(repeatString("-", 40));
System.out.println("要添加的数据:");
System.out.println(" English: 45");
System.out.println(" Math: 89");
System.out.println(" Computer: 100");
RedisOperation.addScofieldRecord();
// 3.2 获取scofield的English成绩
System.out.println("\n3.2 获取scofield的English成绩");
System.out.println(repeatString("-", 40));
RedisOperation.getScofieldEnglishScore();
// 查看所有数据
System.out.println("\n所有学生数据:");
RedisOperation.getAllStudentScores();
// 第四部分:扩展功能与对比
System.out.println("\n" + repeatString("=", 60));
System.out.println("第四部分:扩展功能与数据库对比");
System.out.println(repeatString("=", 60));
// 详细查询
System.out.println("\n各学生详细成绩:");
RedisOperation.queryStudentAllScores("zhangsan");
RedisOperation.queryStudentAllScores("lisi");
RedisOperation.queryStudentAllScores("scofield");
// 统计功能
System.out.println("\n成绩统计:");
RedisOperation.calculateSubjectAverages();
// ==================== 演示总结 ====================
System.out.println("\n" + repeatString("★", 60));
System.out.println(" 实验总结");
System.out.println(repeatString("★", 60));
System.out.println("\n✓ 已完成的Redis操作:");
System.out.println(" 1. 哈希结构的数据设计");
System.out.println(" 2. HSET/HGET/HGETALL命令使用");
System.out.println(" 3. 数据的添加、查询、修改");
System.out.println(" 4. Jedis客户端编程");
System.out.println(" 5. 扩展统计功能");
System.out.println("\n✓ Redis与HBase/MySQL对比:");
System.out.println(" 与MySQL对比:");
System.out.println(" • Redis: 键值存储,内存数据库,速度快");
System.out.println(" • MySQL: 关系型数据库,支持复杂查询");
System.out.println(" 与HBase对比:");
System.out.println(" • Redis: 单机/主从,内存优先");
System.out.println(" • HBase: 分布式,海量数据存储");
System.out.println("\n✓ Redis适用场景:");
System.out.println(" • 缓存系统");
System.out.println(" • 会话存储");
System.out.println(" • 排行榜/计数器");
System.out.println(" • 消息队列");
System.out.println(" • 实时数据分析");
} catch (Exception e) {
System.err.println("演示过程中出现错误: " + e.getMessage());
e.printStackTrace();
} finally {
// 关闭连接池
RedisOperation.close();
}
}
/**
* 重复字符串(兼容Java 1.8)
*/
private static String repeatString(String str, int count) {
if (count <= 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(str);
}
return sb.toString();
}
}

浙公网安备 33010602011771号