Jedis的环境准备
1.先修改配置文件redis.conf
protected-mode :关闭保护模式,允许其他IP主机连接进来
bind:改成0.0.0.0,所有的IP主机都可以进来
2.设置防火墙,让防火墙对端口6379产生的数据进行通信
firewall-cmd --zone=public --add-port=6379 /tcp --permanent
firewall-cmd --reload
3.进入redis官网
点击JAVA↓↓↓
跳转到GitHub后点击releases选择版本↓↓↓本次我们用2.9.0版本
创建一个项目
引入依赖
写一个类
public class JedisTest {
public static void main(String[] args) {
Jedis jedis = new Jedis("你的IP",6379);
try {
//如果你有密码
//jedis.auth("123456")
jedis.select(2);
//新建一个字符串
jedis.set("key01","value01");
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
}
}
利用JSON缓存数据
添加依赖
创建实体类
public class StudentInfo {
private String id;
private String name;
private String sex;
private String age;
public StudentInfo() {
}
public StudentInfo(String id, String name, String sex, String age) {
this.id = id;
this.name = name;
this.sex = sex;
this.age = age;
}
/*
省略getter和setter
*/
public class CacheSample {
public CacheSample(){
Jedis jedis = new Jedis("你的IP");
try {
List<StudentInfo> studentList = new ArrayList<StudentInfo>();
studentList.add(new StudentInfo("1","name1","男","22"));
studentList.add(new StudentInfo("2,","jack","男","22"));
studentList.add(new StudentInfo("3","rose","女","22"));
jedis.select(3);
for(StudentInfo studentInfo : studentList){
//将每一个循环都进行序列化
String json = JSON.toJSONString(studentInfo);
System.out.println("json="+json);
String key = "student:"+studentInfo.getId();
//因为json是字符串
jedis.set(key,json);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
}
public static void main(String[] args) {
new CacheSample();
}
}
将结果转换为JAVA对象
public static void main(String[] args) {
new CacheSample();
Jedis jedis = new Jedis("118.31.69.233");
System.out.println("请输入要查询的学生ID:");
String sc = new Scanner(System.in).next();
String key = null;
try {
key = "student:"+sc;
jedis.select(3);
if(jedis.exists(key)){
String result = jedis.get(key);
//将结果转回JAVA对象
StudentInfo studentInfo =JSON.parseObject(result,StudentInfo.class);
System.out.println(studentInfo.getSex());
System.out.println(studentInfo.getName());
}else {
System.out.println("不存在");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
}
}
Java中使用pipline
1、导包
经过漫长的一段时间,重新学习redis出现的问题以及笔记
在搭建redis集群的时候,发现从节点连接不上主节点。
原因:从机的配置文件中,配置主节点IP的时候,用了replicaof 116.62.xxx.xxx 6379,配置的是公网IP,一直连接不上,后来经过测试,得配置成:replicaof 127.0.0.1 6379就可以搭建好集群了。
这里的原因没有查到,是我还不是很了解网络这一方面的问题,到时候搭建多台机器的集群的时候再处理
java连接不上redis
原因:是因为防火墙6379端口没有开启。
但是在这里我查看了阿里云的防火墙是关闭的,而且在控制台也开放了6379端口,但是始终连不上,于是我尝试开启了防火墙,然后再手动开启6379端口,结果发现连通了,真是太菜了。
开启端口命令:firewall-cmd --zone=public --add-port=6379/tcp --permanent
#开启6379端口
[root@iZbp1ixrdjvxpq8fh7vpauZ redis-5.0.14]# firewall-cmd --zone=public --add-port=6379/tcp --permanent
success
#查看端口开启情况
[root@iZbp1ixrdjvxpq8fh7vpauZ redis-5.0.14]# firewall-cmd --list-ports
6379/tcp
#查看6379端口是否开启
firewall-cmd --query-port=6379/tcp
#重新载入添加的端口
firewall-cmd --reload