SpringBoot中配置redis數據庫及常見錯誤解析——親測通過

一前言:
在本章開始之前,確保自己的Redis是可以成功啓動的,本篇使用的是Windows版本的Redis。
二SpringBoot中配置Redis

  • 1配置POM依賴
  • 2配置配置信息
  • 3封裝常用操作
  • 4進行測試

1配置POM依賴:

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

2配置配置信息

#redis服務器地址
spring.redis.host=127.0.0.1
#redis服務器連接端口
spring.redis.port=6379
#redis服務器連接密碼(默認爲空)
spring.redis.password=
#redis數據庫索引(默認爲0(0-15)
spring.redis.database=0
#redis連接池最大連接數(使用負數則代表沒有連接數沒有限制)
spring.redis.jedis.pool.max-active=11
#redis連接池最大阻塞等待時間
spring.redis.jedis.pool.max-wait=-1
#redis連接池最大空閒連接
spring.redis.jedis.pool.max-idle=11
#redis連接池最小空閒連接
spring.redis.jedis.pool.min-idle=0
#連接超時時間(以毫秒爲單位)
spring.redis.timeout=0

3封裝常用操作

package com.example.xxx.DBTools;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
/*
封裝Redis的常用操作
 */
@Component
public class RedisTools {

    @Autowired
    private RedisTemplate redisTemplate;

    /*
    數據插入
     */
    public boolean set(String key,String value){
        boolean result;
        try{
            redisTemplate.opsForValue().set(key,value);
            result=true;
        }
        catch (Exception e){
            result=false;
            e.printStackTrace();
        }
        return  result;
    }
    /*
    獲取數據
     */
    public String get(String key){
        String result;
        try{
        result=redisTemplate.opsForValue().get(key).toString();
        }catch (Exception e){
            result="獲取失敗";
            e.printStackTrace();
        }
        return result;
    }
    /*
     刪除數據
     */
    public boolean delete(String key){
        boolean result;
        try{
        redisTemplate.delete(key);
        result=true;
        }catch (Exception e){
            result=false;
            e.printStackTrace();
        }
        return result;
    }
}

4進行測試

package com.example.xxx.RedisTools;

import com.example.xxx.DBTools.RedisTools;
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.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class RedisTest {
    @Autowired
    RedisTools redisTools;

    /*
    測試插入方法
     */
    @Test
    public void TestSet(){
        redisTools.set("k2","k2");
    }
}

執行之前:
當前Redis數據庫中是沒有任何數據的:
在這裏插入圖片描述
執行之後:
多了K1這條記錄
在這裏插入圖片描述

注意點:在進行測試的時候,測試類的路徑必須要與該封裝工具類的包名一致,否則就會出現報錯:
Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=…) with your test

連接超時時間設置過短會導致:
java.lang.IllegalStateException: Failed to load ApplicationContext

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章