注:(最終redis數據庫連接信息由使用者項目模塊配置提供)
一、Redis常用存儲操作實現(redis-util模塊,該module最后會打包成jar供其他服務使用)
1.引用相關依賴
- <!-- 如果有繼承父級spring-boot-starter-parent,可不用添加版本號 -->
- <!-- Redis緩存 [start] -->
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-redis</artifactId>
- <version>2.3.0.RELEASE</version>
- </dependency>
- <!-- Redis緩存 [end] -->
2.配置reids連接信息
注:由于此時還處于redis-util工具包開發階段,所以reids的配置文件還是由自己的模塊來提供,后期打包成jar時,會清除redis-util工具包里的redis連接信息,然后由需要使用redis-util工具的服務模塊提供reids的連接信息;
在reids-util的application.properties里配置redis數據庫連接信息
- #Redis服務器地址
- spring.redis.host=127.0.0.1
- #Redis服務器連接端口
- spring.redis.port=6379
- #Redis數據庫索引(默認為0)
- spring.redis.database=0
3.自定義序列化類,將存儲在Redis的對象序列化為json格式
- import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
- import org.springframework.data.redis.serializer.StringRedisSerializer;
- import java.io.Serializable;
- @Configuration
- @EnableAutoConfiguration
- public class RedisConfig {
- @Bean
- public RedisTemplate<String, Serializable> redisTemplate(LettuceConnectionFactory redisConnectionFactory){
- RedisTemplate<String, Serializable> template = new RedisTemplate();
- template.setKeySerializer(new StringRedisSerializer());
- template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
- template.setHashKeySerializer(new StringRedisSerializer());
- template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
- template.setConnectionFactory(redisConnectionFactory);
- return template;
- }
- }
4.開發相應的redis常用方法
- package com.gh.redis.util;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.redis.core.RedisTemplate;
- import org.springframework.stereotype.Repository;
- import org.springframework.util.CollectionUtils;
- import java.io.Serializable;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Set;
- import java.util.concurrent.TimeUnit;
- @Repository
- public class RedisUtil {
- @Autowired
- RedisTemplate<String, Serializable> redisTemplate; // key-value是對象的
- public RedisUtil(){
- }
- /**
- * 判斷是否存在key
- * @param key 主鍵
- * @return true或false
- */
- public boolean hasKey(String key) {
- return Boolean.TRUE.equals(redisTemplate.hasKey(key));
- }
- /**
- * 新增、修改Redis鍵值
- * @param key 主鍵
- * @param value 值
- */
- public void insertOrUpdate(String key, Serializable value) {
- redisTemplate.opsForValue().set(key, value);
- }
- /**
- * 新增、修改Redis鍵值,并設置有效時間(秒)
- * @param key 主鍵
- * @param value 值
- * @param seconds 有效時間(秒)
- */
- public void insertOrUpdateBySeconds(String key, Serializable value, long seconds) {
- redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
- }
- /**
- * 新增、修改Redis鍵值,并設置有效時間(分)
- * @param key 主鍵
- * @param value 值
- * @param minutes 有效時間(分)
- */
- public void insertOrUpdateByMinutes(String key, Serializable value, long minutes) {
- redisTemplate.opsForValue().set(key, value, minutes, TimeUnit.MINUTES);
- }
- /**
- * 新增、修改Redis鍵值,并設置有效時間(小時)
- * @param key 主鍵
- * @param value 值
- * @param hours 有效時間(小時)
- */
- public void insertOrUpdateByHours(String key, Serializable value, long hours) {
- this.redisTemplate.opsForValue().set(key, value, hours, TimeUnit.HOURS);
- }
- /**
- * 新增、修改Redis鍵值,并設置有效時間(天)
- * @param key 主鍵
- * @param value 值
- * @param days 有效時間(天)
- */
- public void insertOrUpdateByDays(String key, Serializable value, long days) {
- this.redisTemplate.opsForValue().set(key, value, days, TimeUnit.DAYS);
- }
- /**
- * 通過主鍵獲取值
- * @param key 主鍵
- * @return
- */
- public Object get(String key) {
- return redisTemplate.opsForValue().get(key);
- }
- /**
- * 獲取redis的所有key里包含pattern字符的key集
- * @param pattern 模糊查詢字符
- * @return
- */
- public Set<String> getPattern(String pattern) {
- return redisTemplate.keys("*" + pattern + "*");
- }
- /**
- * 刪除指定redis緩存
- * @param key 主鍵
- * @return
- */
- public boolean remove(String key) {
- return Boolean.TRUE.equals(redisTemplate.delete(key));
- }
- /**
- * 刪除指定的多個緩存
- * @param keys 主鍵1,主鍵2,...
- * @return 刪除主鍵數
- */
- public int removes(String... keys){
- int count = 0;
- List<String> deleteFails = new ArrayList<>();
- for (String key : keys) {
- if (Boolean.TRUE.equals(redisTemplate.delete(key))) {
- ++count;
- } else {
- deleteFails.add(key);
- }
- }
- if (!CollectionUtils.isEmpty(deleteFails)) {
- System.err.println("======> Redis緩存刪除失敗的key:" + deleteFails.toString());
- }
- return count;
- }
- /**
- * 刪除所有的鍵值對數據
- * @return 清除鍵值對數據量
- */
- public int removeAll(){
- Set<String> keys = redisTemplate.keys("*");
- Long delete = 0L;
- if (keys != null) {
- delete = redisTemplate.delete(keys);
- }
- return delete != null ? delete.intValue() : 0;
- }
- }
5.工具包開發完成,測試一下
- import com.gh.common.toolsclass.ResultData;
- import com.gh.redis.util.RedisUtil;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- import java.util.Set;
- @SpringBootTest
- class RedisApplicationTests {
- @Autowired
- private RedisUtil redisUtil;
- @Test
- void test1() {
- ResultData resultData = new ResultData();
- resultData.setCode(0);
- resultData.setMessage("redis測試");
- resultData.setData("666666");
- redisUtil.insertOrUpdate("demo", resultData);
- System.err.println(redisUtil.hasKey("demo"));
- Object demo = redisUtil.get("demo");
- ResultData bo = (ResultData) demo;
- System.err.println(bo.toString());
- }
- @Test
- void test2() {
- Set<String> list = redisUtil.getPattern("l");
- for (String s: list) {
- System.err.println(s);
- }
- }
- }
其中ResultData是自定義的一個用于返回信息的對象,可用其他對象替代,但是該對象需要實現Serializable接口(ResultData implements Serializable)
運行test1:
運行test2:
其他方法自行測試,這里不一 一展示;
6.清除redis數據庫連接信息
自此redis-util工具包開發完成,可供其他服務使用,最后清除redis-util模塊application.properties里的redis數據庫連接信息。之后的連接信息由使用者模塊提供,這樣才符合redis-util作為一個純工具包的定義。
二、創建一個consumer項目來引用redis-util工具包
1.在consumer項目的pom.xml中添加reids-utils的依賴
- <!-- redis工具包 [start] -->
- <dependency>
- <groupId>com.gh</groupId>
- <artifactId>redis-util</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- </dependency>
- <!-- redis工具包 [end] -->
pom如何引用自定義jar包依賴自行百度,如果在同一父工程模塊下,可直接這么引用。不在同一父工程,需要先將jar包放到maven倉庫。
2.在consumer的application.properties配置文件里添加redis數據的連接信息
- #Redis服務器地址
- spring.redis.host=127.0.0.1
- #Redis服務器連接端口
- spring.redis.port=6379
- #Redis數據庫索引(默認為0)
- spring.redis.database=0
3.測試在cunsumer里是否可以使用redis-util工具包的方法
- package com.gh.consumer;
- import com.gh.common.toolsclass.ResultData;
- import com.gh.redis.util.RedisUtil;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
- @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
- class ConsumerApplicationTests {
- // 這里使用該構造器注入的方式,因為使用變量注入
- final RedisUtil redisUtil;
- @Autowired
- public ConsumerApplicationTests(RedisUtil redisUtil){
- this.redisUtil = redisUtil;
- }
- @Test
- void test1() {
- // 如果存在demo緩存,就刪除
- if (redisUtil.hasKey("demo")) {
- System.err.println(redisUtil.remove("demo"));
- }
- // 插入新的demo緩存
- ResultData resultData = new ResultData();
- resultData.setCode(0);
- resultData.setMessage("redis測試-2");
- resultData.setData("888888");
- redisUtil.insertOrUpdate("demo", resultData);
- Object demo = redisUtil.get("demo");
- ResultData bo = (ResultData) demo;
- System.err.println(bo.toString());
- }
- @Test
- void test2() {
- redisUtil.insertOrUpdate("test", "redis工具測試");
- System.err.println(redisUtil.get("test"));
- }
- }
運行test1,此時會發現控制臺提示找不到RedisUtil的bean
4.在啟動類添加掃描
其他注解不用管,解決redis-util工具包bean掃描不到的問題,只需要添加注解@ComponentScan(value = “com.gh.redis.*”)就好
- package com.gh.consumer;
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- //import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
- import org.springframework.cloud.openfeign.EnableFeignClients;
- import org.springframework.context.annotation.ComponentScan;
- import org.springframework.context.annotation.ComponentScans;
- import org.springframework.scheduling.annotation.EnableScheduling;
- //@EnableDiscoveryClient eureka開啟發現服務功能
- @EnableFeignClients(basePackages = "com.gh.consumer.feign")
- //@ComponentScan(basePackages = "com.gh.consumer.*")
- @ComponentScans(value = {
- @ComponentScan(value = "com.gh.consumer.*")
- ,@ComponentScan(value = "com.gh.redis.*")
- })
- @EnableScheduling // 開啟定時任務功能
- @SpringBootApplication
- public class ConsumerApplication {
- public static void main(String[] args) {
- SpringApplication.run(ConsumerApplication.class, args);
- }
- }
5.再次測試
成功調用redis-utils工具包方法!
到此這篇關于如何自定義redis工具jar包供其他SpringBoot項目直接使用的文章就介紹到這了,更多相關redis工具jar包springboot使用內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!