Linux学习-Jedis学习
Posted 丢爸
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Linux学习-Jedis学习相关的知识,希望对你有一定的参考价值。
通过Jedis访问Redis数据库(通过Idea来访问redis数据库)
- 使用Idea创建一个maven项目
- 引入jedis依赖
//在pom.xml文件中的dependencies标签中加入jedis和junit依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>3.7.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
- 创建测试文件
package com.frs;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;
import java.util.Map;
public class FirstRedis
private Jedis jedis;
@BeforeEach
void setUp()
jedis=new Jedis("192.168.115.129",6379);
jedis.auth("123123");
jedis.select(0);
@Test
void testString()
jedis.set("username","zhangsan");
System.out.println(jedis.keys("*"));
@Test
void testHash()
jedis.hset("user1","username","jack");
jedis.hset("user1","age","23");
Map<String,String> user1=jedis.hgetAll("user1");
System.out.println(user1);
@AfterEach
void close()
if(jedis !=null)
jedis.close();
- jedis连接池
//jedis本身是线程不安全的,并且频繁的创建和销毁连接会有性能损耗,推荐使用jedis连接池连接redis数据库
//创建一个Jedis连接池
package com.frs;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class JedisConnectionFactory
private static final JedisPool jedisPool;
static
JedisPoolConfig jedisPoolConfig=new JedisPoolConfig();
//最大连接
jedisPoolConfig.setMaxTotal(8);
//最大空闲连接
jedisPoolConfig.setMaxIdle(8);
//最小空闲连接
jedisPoolConfig.setMinIdle(0);
//设置最长等待时间,ms
jedisPoolConfig.setMaxWaitMillis(200);
jedisPool=new JedisPool(jedisPoolConfig,"192.168.115.129",6379,1000,"123123");
//返回jedis对象
public static Jedis getJedis()
return jedisPool.getResource();
//使用连接池来创建jedis测试
package com.frs;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;
import java.util.Map;
public class SecondRedis
private Jedis jedis;
@BeforeEach
void setUp()
jedis=JedisConnectionFactory.getJedis();
jedis.select(0);
@Test
void testString()
jedis.set("username","zhangsan");
System.out.println(jedis.keys("*"));
@Test
void testHash()
jedis.hset("user1","username","jack");
jedis.hset("user1","age","23");
Map<String,String> user1=jedis.hgetAll("user1");
System.out.println(user1);
@AfterEach
void close()
if(jedis !=null)
jedis.close();
以上是关于Linux学习-Jedis学习的主要内容,如果未能解决你的问题,请参考以下文章