您的位置:首页 > 数据库 > Redis

SpringBoot整合Redis

2020-06-29 04:26 148 查看

1.Redis安装

Redis大部分情况下是使用在Linux环境下,具体安装可参考

2.SpringBoot整合Redis

1.创建SpringBoot项目

pom.xml添加如下依赖

[code]<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.在resources目录下的application.properties配置文件中配置连接Redis的信息,主要说一下password属性,如果Redis的启动配置文件里开启了requirepass xxx则需要在application.properties里配置password,如果Redis里没有配置,则application.propertes里也不能配置password属性。

[code]#Redis里默认数据库编号
spring.redis.database=0
#虚拟机ip
spring.redis.host=192.168.2.10
#要连接的Redis实例端口
spring.redis.port=6379
#连接密码
spring.redis.password=xxx
#一些连接池信息
spring.redis.lettuce.pool.min-idle=5
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=1ms
spring.redis.lettuce.shutdown-timeout=100ms

3.创建一个HelloService来实现对Redis的操作

[code]@Service
public class HelloService {
@Autowired
RedisTemplate redisTemplate;
public void hello(){
ValueOperations ops = redisTemplate.opsForValue();
ops.set("k2","v2");
Object k1 = ops.get("k2");
System.out.println(k1);
}
}

4.进行测试

[code]@SpringBootTest
class SsoApplicationTests {
@Autowired
HelloService helloService;
@Test
void testRedis(){
helloService.hello();
}
}

 测试成功,控制台会打印“v2”。Linux中登录Redis客户端也可以查看我们刚刚存入的数据

 上图中存入的数据的key怎么不是k2,这个跟RedisTemplate的序列化方式有关,还有一个叫StringRedisTemplate,它存入到Redis的数据显示的是key的原型。

Redis中的数据操作可分为两种

(1)针对key的操作,相关的方法就在RedisTemplate中

(2)针对具体数据类型的操作,相关的方法需要先获取对应的数据类型,获取方式是opsForXXX

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: