NoSQL第二次作业(3)
数据库端建立redis 集群,可参照ppt里仅使用redis命令创建集群,集群的分片由集群维护,Java客户端连接集群即可
用到的类主要有:redis.clients.jedis.JedisCluster,实现增删改查
集群配置
port 6383/6384/6385 //修改为与当前文件夹名字一样的端口号
appendonly yes //指定是否在每次更新操作后进行日志记录,Redis在默认情况下是异步的把数据写入磁盘,如果不开启,可能会在断电时导致一段时间内的数据丢失。 yes表示:存储方式,aof,将写操作记录保存到日志中
cluster-enabled yes //开启集群模式
cluster-config-file nodes-6380.conf //保存节点配置,自动创建,自动更新(建议命名时加上端口号)
cluster-node-timeout 15000 //集群超时时间,节点超过这个时间没反应就断定是宕机
开启redis
redis-server.exe redis.windows6383.conf
redis-server.exe redis.windows6384.conf
redis-server.exe redis.windows6385.conf
third.java
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import java.util.HashSet;
import java.util.Set;
public class third {
private Set<HostAndPort> set;
private JedisCluster getConnection() {
return new JedisCluster(set);
}
public void insert(String key, String value) throws Exception {
JedisCluster connection = getConnection();
String value1 = connection.get(key);
if(connection.get(key) != null) {
connection.close();
throw new Exception("插入失败,已经有名为"+key+"的键"+ ",value:" + value1);
}
else {
connection.set(key, value);
System.out.println("成功插入一组键值对" + "key:" + key + ",value:" + value);
}
connection.close();
}
public void delete(String key) throws Exception {
JedisCluster connection = getConnection();
String value = connection.get(key);
if(connection.get(key) == null) {
connection.close();
throw new Exception("删除失败,不存在名为"+key+"的键"+ ",value:" + value);
}
else {
System.out.println("成功删除一组键值对" + "key:" + key + ",value:" + value);
connection.del(key);
}
connection.close();
}
public void update(String key, String value) throws Exception {
JedisCluster connection = getConnection();
if(connection.get(key) == null) {
String value1 = connection.get(key);
connection.close();
throw new Exception("更新失败,不存在名为"+key+"的键"+ ",value:" + value1);
}
else {
connection.set(key, value);
System.out.println("成功更新一组键值对" + "key:" + key + ",value:" + value);
}
connection.close();
}
public String query(String key) {
JedisCluster connection = getConnection();
String value = connection.get(key);
String result = null;
if(value == null) {
System.out.println("查询结果,不存在名为"+key+"的键");
}
else {
result = value;
System.out.println("成功查找一组键值对"+"key:"+key+",value:"+value);
}
connection.close();
return result;
}
@SuppressWarnings("resource")
@Test
public void third() {
Set<HostAndPort> port = new HashSet<>();
port.add(new HostAndPort("localhost", 6383));
port.add(new HostAndPort("localhost", 6384));
port.add(new HostAndPort("localhost", 6385));
this.set = port;
try {
insert("name", "test1");
}
catch(Exception e) {
System.out.println(e.getMessage());
}
try {
update("name", "test3");
}
catch(Exception e) {
System.out.println(e.getMessage());
}
try {
query("name");
}
catch(Exception e) {
System.out.println(e.getMessage());
}
try {
delete("name");
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}