SpringBoot 引入redis
Redis是一個記憶體資料庫,可以把需要經常訪問的資料快取到Redis,可以大大提高訪問效率。
下面介紹一下使用方法:
1.安裝windows版redis
由於windows的redis僅僅用於個人測試玩耍,這裡就簡單下載zip解壓版本,相關配置項也不在這裡贅述,參考linux下redis的介紹
點選下載:https://github.com/MicrosoftArchive/redis/releases
下載後解壓;
在解壓所在目錄使用如下命令啟動服務端:(由於這裡使用的win10的powershell,所以需要新增./,或者配置環境變數也可以避免使用./)
./redis-server.exe redis.windows.conf
//這裡就不將其註冊為windows服務了,關閉視窗,也就關閉了redis
啟動命令端:
./redis-cli.exe -h 127.0.0.1 -p 6379
2.引入依賴
<!-- springboot整合redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
這裡只需引入這一個redis的依賴即可,其他3個自動進行了依賴:
3.在application.yml中配置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=30000
4.把Redis註冊為本地服務
通常情況下我們可以通過 redis-server.exe 和配置檔案啟動redis服務 :
redis-server.exe redis.windows.conf
另外開啟一個命令列視窗 redis-cli.exe 即可做一些簡單的操作命令列
但如果我們關閉控制檯,那麼Redis服務也跟隨著一起關閉了,想使用的時候又得執行命令重新開啟動redis 服務,是非常低效又麻煩的。
在Windows中有個本地服務的概念,我們的目標就是將Redis註冊成這裡面的一個服務,然後就可以不受控制檯退出的影響了。
註冊為本地服務:
redis-server.exe--service-installredis.windows.conf
從圖中看到已成功授權並且註冊成功,接下來,我們到windows服務(右鍵單擊windows選單-》計算機管理-》服務和應用程式-》服務)中去看一下是否有redis服務:
命令規整
註冊服務 redis-server --service-install redis.windows.conf
刪除服務 redis-server --service-uninstall
開啟服務 redis-server --service-start
停止服務 redis-server --service-stop
5.Redis的使用
@Autowired private StringRedisTemplate redisTmp; @GetMapping("/api/setkey") public String setkey(String keyname,String keyvalue){ String value = "Set Value OK"; try{ redisTmp.opsForValue().set(keyname,keyvalue); }catch (Exception ex){ value = "Set Error :"+ex.getMessage(); } return value; } @GetMapping("/api/getkey") public String getkey(String keyname){ String str = ""; try { Boolean isHas = redisTmp.hasKey(keyname); if (isHas){ str = redisTmp.opsForValue().get(keyname).toString(); }else { str = "抱歉!不存在key值為"+keyname; } } catch (Exception ex){ str = ex.getMessage(); } return str; }
參考:
1.https://www.cnblogs.com/jiangbei/p/8601107.html
2.https://www.cnblogs.com/wasonzhao/p/12758590.html
3.https://blog.csdn.net/weixin_40623736/article/details/98097708