使用spring-boot-starter-data-redis访问redis入门示例(默认使用Lettuce)

1、 引入依赖

	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-data-redis</artifactId>
	</dependency>

需要注意:
官方默认使用的是Lettuce,不是Jedis。

可以看到spring-boot-starter-data-redis内部只引入了lettuce的依赖。
在这里插入图片描述
如果想要使用Jedis,在官方指南中有说明 [传送门]

2、redis基本配置

在application.properties文件中配置redis信息。

# ############################ Redis配置 #########################
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.224.130
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=password
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=20000
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=20000

3、使用RedisTemplate操作Redis

package com.tao.springboot.demo;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {SpringbootDemoApplication.class}) // 必需指定启动类
public class SpringbootDemoApplicationTests {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	@Test
	public void contextLoads() {
	}
	
	@Test
	public void testRedis() {
		redisTemplate.opsForValue().set("name", "zhangsan");
		Assert.assertEquals("zhangsan", redisTemplate.opsForValue().get("name"));
	}

}
发布了178 篇原创文章 · 获赞 152 · 访问量 61万+

猜你喜欢

转载自blog.csdn.net/hbtj_1216/article/details/96652605