SpringBoot整合Redis
  • 2024-12-26 09:22:42
  • 897 热度
  • 0 评论

首先,你要有一个Redis服务,本地建一个用于测试,参考

windows下安装redis及其客户端

http://www.javacui.com/tool/513.html 

redis的配置文件介绍

http://www.javacui.com/tool/514.html 


SpringBoot中引入Redis,pom.xml中添加

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


application.properties中配置连接

spring.redis.host=127.0.0.1
spring.redis.port=6379
# Redis服务器连接密码(默认为空,但是该字段必须设置) 
spring.redis.password=
# Redis数据库索引(默认为0)
spring.redis.database=1
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=10
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=1
# 连接超时时间(毫秒)
spring.redis.timeout=1000


这里说一个坑spring.redis.password=这个配置,虽然Redis没有密码,但是这个配置必须在,不能注释不能删除,否则报错连接不上Redis。


使用StringRedisTemplate实现对Redis的操作

package com.example.demo.redis;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
/**
 * Redis工具类
 */
@Repository
public class RedisDao {
	@Autowired
    private StringRedisTemplate template;
    public  void setKey(String key,String value){
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key,value,1, TimeUnit.MINUTES);//1分钟过期
    }
    public String getValue(String key){
        ValueOperations<String, String> ops = this.template.opsForValue();
        return ops.get(key);
    }
}

我特别讨厌网上发代码不发import的人。

使用时注入这个工具类即可

@Autowired
RedisDao redisDao;


配图

END


Flame

Hello world!

0 评论
留下评论