Jedis使用

网友投稿 530 2022-05-30

前言

阅读本文之后读者将会学习到如何使用java调用redis。

开发环境包括idea、maven、jdk1.8、redis。

本文假设读者已经在本机搭建好了redis服务器,并开放端口为6379,如果还未完成该操作请参考相关文档搭建redis服务器。

redis可以使用docker快速使用,命令:

docker run --name some-redis -p 6379:6379 -d redis:4

Jedis的使用

操作步骤

创建工程

使用idea选用maven创建一个spring boot工程,如读者不清楚操作步骤,可参考该idea 新建spring boot项目。

修改pom.xml文件

在pom.xml文件中加入testng以及redis相关依赖 .

org.testng testng 6.8 test redis.clients jedis 2.9.0

创建资源配置文件testredis/src/main/resources/db.yaml

redis: maxId: 40 minId: 10 maxTotal: 70 ip: 127.0.0.1 port: 6379

创建工具类com.nick.testredis.util.RedisDBUtils

public class RedisDBUtils { private static JedisPool jedisPool = null; //获取数据源信息 static { ResourceBundle bundle = ResourceBundle.getBundle("db"); JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMinIdle(Integer.parseInt(bundle.getString("redis.maxId"))); jedisPoolConfig.setMaxIdle(Integer.parseInt(bundle.getString("redis.minId"))); jedisPoolConfig.setMaxTotal(Integer.parseInt(bundle.getString("redis.maxTotal"))); jedisPool = new JedisPool(jedisPoolConfig,bundle.getString("redis.ip"), Integer.parseInt(bundle.getString("redis.port"))); } public static Jedis getJedis(){ return jedisPool.getResource(); } }

在test下面创建测试类com.nick.testredis.Test

@org.testng.annotations.Test public class Test { //使用一般连接 @org.testng.annotations.Test public void test(){ Jedis jedis = new Jedis("127.0.0.1",6379); String name = jedis.get("name"); System.out.println(name); jedis.set("name","hello3"+name); String name1 = jedis.get("name"); System.out.println(name1); } //使用连接池 @org.testng.annotations.Test public void getTestRedis(){ JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); //最大和最小空闲数 jedisPoolConfig.setMaxIdle(30); jedisPoolConfig.setMinIdle(10); //最大连接数 jedisPoolConfig.setMaxTotal(60); //新建一个连接池 JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379); Jedis resource = jedisPool.getResource(); String string = resource.get("name"); System.out.println("name>>"+ string); resource.close(); jedisPool.close(); } @org.testng.annotations.Test public void useRedisDBUtils(){ Jedis jedis = RedisDBUtils.getJedis(); String string = jedis.get("name"); System.out.println("name1>>"+ string); jedis.close(); } }

完成该步骤之后,可以右键运行查看效果。

总结

本文介绍了如何使用jedis连接redis服务器,并做简单的读谢操作。完整代码见github工程

Redis Spring

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:《Office 2019高效办公三合一从入门到精通 : 视频自学版》 —1.4.3自定义快速访问工具栏
下一篇:【模型评估(一)】AI市场模型评估端到端流程打通
相关文章