最近西安的雾霾天又来了,西安的雾霾古朴浑厚,如果你能扛过西安冬季的雾霾而不咳嗽,恭喜你,新冠也奈何不了你。其实夏季的西安还是非常不错的
今天我们就看一下Spring boot集成Redis开发,首先我们下载Redis windows版本,解压之后如下
接下来我们修改redis密码,打开redis.windows.conf文件,将需要密码的注释去掉,并将密码设置为123456,
然后使用命令:redis-server redis.windows.conf 启动redis
启动成功后,然后我们使用redis cli连接redis server。
发现redis提示没有权限,因为我们刚才启动的时候指定了redis启动要加载的config文件,因为config文件中放开了必须输入密码的注释,所以这里我们必须进行身份认证,输入auth {password}
我们发现已经成功了,OK,接下来我们就看一下在Spring boot框架下如何读写redis。
首先我们的pom文件新增maven依赖如下
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.2.10.RELEASE</version> </dependency>
接着我们修改application.properties文件,增加redis的配置
spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=19861017 spring.redis.pool.max-active=8 spring.redis.pool.max-wait=-1 spring.redis.pool.max-idle=10 spring.redis.pool.min-idle=0 spring.redis.timeout=30000
IP,端口,最大连接数,最大等待数,最大限制连接,超时时间等。配置完之后我们就从controller开始看,新增两个api
@PostMapping(value = "create/redis", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) public void createTechArticleByRedis(@RequestBody TechArticle techArticle) { techArticleService.createTechArticleByRedis(techArticle); } @GetMapping("retrieve/redis/{key}") public TechArticle getTechArticleByRedis(@PathVariable("key") String key) { return techArticleService.getTechArticleByRedis(key); }
接下来我们看一下service层
public void createTechArticleByRedis(TechArticle techArticle) { redisUtil.set("techarticle", techArticle, 300); } public TechArticle getTechArticleByRedis(String key) { return (TechArticle)redisUtil.get(key); }
非常简单,没啥说的,就是个调用而已,接下来我们需要按照约定创建一个redisConfig文件,返回一个RedisTemplate对象,没办法这个是约定编程,必须要写的
@Configuration @EnableCaching //开启注解 public class RedisConfig extends CachingConfigurerSupport { /** * retemplate相关配置 * @param factory * @return */ @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<>(); // 配置连接工厂 template.setConnectionFactory(factory); Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会抛出异常 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jacksonSeial.setObjectMapper(om); // 值采用json序列化 template.setValueSerializer(jacksonSeial); //使用StringRedisSerializer来序列化和反序列化redis的key值 template.setKeySerializer(new StringRedisSerializer()); // 设置hash key 和value序列化模式 template.setHashKeySerializer(new StringRedisSerializer()); template.setHashValueSerializer(jacksonSeial); template.afterPropertiesSet(); return template; } }
接下来我们再看一下redisUtil的set和get方法
public boolean set(String key,Object value,long time){ try { if(time>0){ redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); }else{ set(key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } public boolean set(String key,Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; }
这里大家注意redisTemplate.opsForValue()他返回一个ValueOperations对象,这个对象又包含了很多方法
void set(K key, V value); void set(K key, V value, long timeout, TimeUnit unit); default void set(K key, V value, Duration timeout) { Assert.notNull(timeout, "Timeout must not be null!"); if (TimeoutUtils.hasMillis(timeout)) { this.set(key, value, timeout.toMillis(), TimeUnit.MILLISECON } else { this.set(key, value, timeout.getSeconds(), TimeUnit.SECONDS) } } @Nullable Boolean setIfAbsent(K key, V value); @Nullable Boolean setIfAbsent(K key, V value, long timeout, TimeUnit unit); @Nullable default Boolean setIfAbsent(K key, V value, Duration timeout) { Assert.notNull(timeout, "Timeout must not be null!"); return TimeoutUtils.hasMillis(timeout) ? this.setIfAbsent(key, v } @Nullable Boolean setIfPresent(K key, V value); @Nullable Boolean setIfPresent(K key, V value, long timeout, TimeUnit unit); @Nullable default Boolean setIfPresent(K key, V value, Duration timeout) { Assert.notNull(timeout, "Timeout must not be null!"); return TimeoutUtils.hasMillis(timeout) ? this.setIfPresent(key, } void multiSet(Map<? extends K, ? extends V> map); @Nullable Boolean multiSetIfAbsent(Map<? extends K, ? extends V> map); @Nullable V get(Object key); @Nullable V getAndSet(K key, V value); @Nullable List<V> multiGet(Collection<K> keys); @Nullable Long increment(K key); @Nullable Long increment(K key, long delta); @Nullable Double increment(K key, double delta); @Nullable Long decrement(K key); @Nullable Long decrement(K key, long delta); @Nullable Integer append(K key, String value); @Nullable String get(K key, long start, long end); void set(K key, V value, long offset); @Nullable Long size(K key); @Nullable Boolean setBit(K key, long offset, boolean value); @Nullable Boolean getBit(K key, long offset); @Nullable List<Long> bitField(K key, BitFieldSubCommands subCommands); RedisOperations<K, V> getOperations();
因此我们可以使用这些方法做一些操作,对于这些方法具体什么含义,网上一搜一大堆,我就不再赘述。ok我们看一下api请求
我们在cli看一下结果,我的乖乖,居然是乱码
翻了一下资料,我们需要在cli加上参数如下
还是乱码,后面再看吧。PostMan请求一下,没问题