开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第18天,点击查看活动详情
Jedis连接和安装
1.修改redis.conf配置
- 绑定端口改成0.0.0.0
- 关闭保护模式
2.防火墙处理
- 防火墙添加6379端口
firewall-cmd --zone=public --add-port=6379/tcp --permanent
- 重启防火墙
firewall-cmd --reload
3.启动redis
- 查看端口
4.新建工程
- pom.xml引入redis客户端
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
- 成功引入之后
- 连接redis(看到控制台输出redi连接成功,说明我们配置成功了)
5.设置key-value
代码说明:
jedis.set("fruit","apple");
jedis.mset(new String[]{"age","18","name","xiaoming"});
System.out.println(jedis.mget(new String[]{"age","name","fruit"}));
代码说明:
- jedis.set("fruit","apple"); :设置key和value
- jedis.mset(new String[]{"age","18","name","xiaoming"});:设置多个key
- jedis.mget(new String[]{"age","name","fruit"}):批量获取key
6.hash使用
jedis.hset("student:1","name","xiaoming");
System.out.println(jedis.hget("student:1","name"));
Map student = new HashMap<>();
student.put("name","hua");
student.put("age","80");
jedis.hmset("student",student);
System.out.println(jedis.hgetAll("student"));
代码说明:
- jedis.hset("student:1","name","xiaoming");:设置单独的hashMap,第一个是hash的名字,其他为key,val,key2,val2
- jedis.hmset("student",student);:student是hashMap的对象
7.list使用
jedis.del("list");
jedis.lpush("list",new String []{"a","b","c"});
jedis.rpush("list",new String[]{"h","i","j"});
//移出
jedis.lpop("list");
System.out.println(jedis.lrange("list",0 ,-1));
8.fastjson使用
pom中引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
List<Goods> goodsList = new ArrayList<>();
goodsList.add(new Goods(1L,"test"));
goodsList.add(new Goods(2L,"haha"));
for (Goods goods:goodsList){
String json = JSON.toJSONString(goods);
String key = "good:"+String.valueOf(goods.getGoodsId());
jedis.set(key,json);
}
//取出json
String goodKey = "good:1";
String goods = jedis.get(goodKey);
System.out.println(goods);
Goods goods1 = JSON.parseObject(goods,Goods.class);
System.out.println(goods1.getGoodsName());
代码说明:
- JSON.toJSONString(goods):对象转成json
- JSON.parseObject(goods,Goods.class):json转对象