Jedis的使用
【摘要】 前言阅读本文之后读者将会学习到如何使用java调用redis。开发环境包括idea、maven、jdk1.8、redis。本文假设读者已经在本机搭建好了redis服务器,并开放端口为6379,如果还未完成该操作请参考相关文档搭建redis服务器。redis可以使用docker快速使用,命令:docker run --name some-redis -p 6379:6379 -d redis:...
前言
阅读本文之后读者将会学习到如何使用java调用redis。
开发环境包括idea、maven、jdk1.8、redis。
本文假设读者已经在本机搭建好了redis服务器,并开放端口为6379,如果还未完成该操作请参考相关文档搭建redis服务器。
redis可以使用docker快速使用,命令:
docker run --name some-redis -p 6379:6379 -d redis:4
操作步骤
创建工程
使用idea选用maven创建一个spring boot工程,如读者不清楚操作步骤,可参考该idea 新建spring boot项目。
修改pom.xml文件
在pom.xml文件中加入testng以及redis相关依赖 .
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
创建资源配置文件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.Testpublic 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工程
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)