本篇文章为大家展示了怎么在SpringBoot项目中使用redis工具jar包,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
一、Redis常用存储操作实现(redis-util模块,该module最后会打包成jar供其他服务使用)
引用相关依赖
<!-- 如果有继承父级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] -->
配置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
自定义序列化类,将存储在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@EnableAutoConfigurationpublic 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; }}
开发相应的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;@Repositorypublic class RedisUtil { @Autowired RedisTemplate<String, Serializable> redisTemplate; // key-value是对象的 public RedisUtil(){ } public boolean hasKey(String key) { return Boolean.TRUE.equals(redisTemplate.hasKey(key)); } public void insertOrUpdate(String key, Serializable value) { redisTemplate.opsForValue().set(key, value); } public void insertOrUpdateBySeconds(String key, Serializable value, long seconds) { redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS); } public void insertOrUpdateByMinutes(String key, Serializable value, long minutes) { redisTemplate.opsForValue().set(key, value, minutes, TimeUnit.MINUTES); } public void insertOrUpdateByHours(String key, Serializable value, long hours) { this.redisTemplate.opsForValue().set(key, value, hours, TimeUnit.HOURS); } public void insertOrUpdateByDays(String key, Serializable value, long days) { this.redisTemplate.opsForValue().set(key, value, days, TimeUnit.DAYS); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } public Set<String> getPattern(String pattern) { return redisTemplate.keys("*" + pattern + "*"); } public boolean remove(String key) { return Boolean.TRUE.equals(redisTemplate.delete(key)); } 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; } public int removeAll(){ Set<String> keys = redisTemplate.keys("*"); Long delete = 0L; if (keys != null) { delete = redisTemplate.delete(keys); } return delete != null ? delete.intValue() : 0; }}
工具包开发完成,测试一下
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;@SpringBootTestclass 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:
其他方法自行测试,这里不一 一展示;
清除redis数据库连接信息
自此redis-util工具包开发完成,可供其他服务使用,最后清除redis-util模块application.properties里的redis数据库连接信息。之后的连接信息由使用者模块提供,这样才符合redis-util作为一个纯工具包的定义。
二、创建一个consumer项目来引用redis-util工具包
在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仓库。
在consumer的application.properties配置文件里添加redis数据的连接信息
#Redis服务器地址spring.redis.host=127.0.0.1#Redis服务器连接端口spring.redis.port=6379#Redis数据库索引(默认为0)spring.redis.database=0
测试在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
在启动类添加扫描
其他注解不用管,解决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// 开启定时任务功能@SpringBootApplicationpublic class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}}
再次测试
上述内容就是怎么在SpringBoot项目中使用redis工具jar包,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注编程网行业资讯频道。