springboot整合redis


這幾天正好新項目中用到了redis,在網上搜了一下,總結一下

網上有兩種,一種是不用配置文件,用類來配置管理redis,另一種是寫在yaml或者properties中

我感覺卸載yaml中的方式比較直觀,簡單,下面來簡單介紹一下,挺簡單的

1.我們項目用的是springboot2.0,然后在pom中引入redis依賴,格式如下

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

2.在你的類中注入

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

或者

    @Autowired
    private RedisTemplate redisTemplate;

然后保存key,取key,設置超時時間等等吧,其他類型的用法百度就行了,很多。

使用:redisTemplate.opsForValue().set("name","tom");
結果:redisTemplate.opsForValue().get("name")  輸出結果為tom

哦,對了,在properties中加入基本的配置文件

# Redis數據庫索引(默認為0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=127.0.0.1
# Redis服務器連接端口
spring.redis.port=6379
# Redis服務器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=5000

然后還有一種就是搜索所有近似的key

stringRedisTemplate.keys("xxx")

這種用法在生產環境中一定不要用,除非數據量很小。。。

 


 

 

常用用法:

1.map格式

Map<String, String> map = new HashMap<String, String>();
map.put("ID", questionId);
map.put("JUDGE_RESULT", radioValue);
stringRedisTemplate.opsForHash().putAll("newKey", map);
// 設置鍵的超時時間,單位秒
stringRedisTemplate.expire("newKey", 120, TimeUnit.SECONDS);
// 刪除鍵
Boolean flag = stringRedisTemplate.delete("newKey");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM