一 jedis的基本使用
1.什么是 Jedis?
Jedis 是redis的 java版,可以使用Jedis提供的API来对redis进行操作,Jedis对于redis的支持非常全面且灵活,但是编码复杂度较高。
2.基本使用
2.1导入Jedis相关的依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.2创建连接池,从连接池里面拿到对象进行连接
@Test
public void testJedisPool() {
// 1:创建Jedis连接池
JedisPool pool = new JedisPool("localhost", 6379);
// 2:从连接池中获取Jedis对象
Jedis jedis = pool.getResource();
/* 设置密码
jedis.auth(密码); */
// 3:TODO
jedis.set("小李","java");
System.out.println(jedis.get("小李"));
// 4:关闭资源
jedis.close();
pool.destroy();
}
2.3设置连接池的参数去进行连接池的配置
@Test
public void testTool(){
GenericObjectPoolConfig config = new GenericObjectPoolConfig();
最大连接数, 默认8个
config.setMaxTotal(100);
最大空闲连接数, 默认8个
config.setMaxIdle(20);
//获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1
config.setMaxWaitMillis(-1);
//在获取连接的时候检查有效性, 默认false
config.setTestOnBorrow(true);
JedisPool pool = new JedisPool(config,"192.168.122.128",6379,5000,"wolfcode");
Jedis j = pool.getResource();
String name = j.get("name");
System.out.println(name);
j.close();
pool.close();
pool.destroy();
}
二 集成springboot的基本使用
1.什么是SpringDataRedis
是一个Spring
官方提供的供我们操作Redis
的一个库。它提供了RedisTemplate
统一的API来操作Redis
2.基本使用
2.1 导入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.2修改配置文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2.3进行测试
@Autowired
private StringRedisTemplate redisTemplate;
@Test
public void testRedisTemplate() {
// 操作string字符串
redisTemplate.opsForValue().xx();
// 操作hash
redisTemplate.opsForHash().xx();
// 操作list
redisTemplate.opsForList().xx();
// 操作set
redisTemplate.opsForSet().xx();
// 操作有序zset
redisTemplate.opsForZSet().xx();
}