知识点科普

REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统。

Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。

它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Hash), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。

windows下安装redis

下载地址:https://github.com/microsoftarchive/redis/releases/tag/win-3.2.100

打开cmd窗口,使用cd命令切换到D:\Redis-x64-3.2.100运行:

redis-server.exe redis.windows.conf

redis启动成功;

spring-boot集成redis

1.引入maven依赖:

<!--集成redis-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-redis</artifactId><version>1.4.1.RELEASE</version>
</dependency>
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.3</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId>
</dependency>

2.在配置中心里添加redis配置

## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## 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=1200

3.配置类LettuceRedisConfig

import org.springframework.context.annotation.Configuration;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @ClassName: LettuceRedisConfig* @Description: Lettuce Redis配置* @author yunxi.shi* @date 2020年2月11日 上午9:36:57*/
@Configuration
public class LettuceRedisConfig {@Bean@ConditionalOnClass(RedisOperations.class)public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper mapper = new ObjectMapper();mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);mapper.activateDefaultTyping(mapper.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(mapper);StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();// key采用 String的序列化方式template.setKeySerializer(stringRedisSerializer);// hash的 key也采用 String的序列化方式template.setHashKeySerializer(stringRedisSerializer);// value序列化方式采用 jacksontemplate.setValueSerializer(jackson2JsonRedisSerializer);// hash的 value序列化方式采用 jacksontemplate.setHashValueSerializer(jackson2JsonRedisSerializer);template.afterPropertiesSet();return template;}}

4.定义常用的 Redis操作

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** @ClassName: RedisService* @Description: 定义常用的 Redis操作* @author yunxi.shi* @date 2020年2月11日 上午9:39:24*/
@Service
public class RedisService {@Autowiredprivate RedisTemplate<String, Object> redisTemplate;/*** 指定缓存失效时间** @param key  键* @param time 时间(秒)* @return Boolean*/public Boolean expire(String key, Long time) {try {if (time > 0) {redisTemplate.expire(key, time, TimeUnit.SECONDS);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据key获取过期时间** @param key 键 不能为 null* @return 时间(秒) 返回 0代表为永久有效*/public Long getExpire(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);}/*** 判断 key是否存在** @param key 键* @return true 存在 false不存在*/public Boolean hasKey(String key) {try {return redisTemplate.hasKey(key);} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除缓存** @param key 可以传一个值 或多个*/public void del(String... key) {if (key != null && key.length > 0) {if (key.length == 1) {redisTemplate.delete(key[0]);} else {redisTemplate.delete(Arrays.asList(key));}}}/*** 普通缓存获取** @param key 键* @return 值*/public Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}/*** 普通缓存放入** @param key   键* @param value 值* @return true成功 false失败*/public Boolean set(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 普通缓存放入并设置时间** @param key   键* @param value 值* @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/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;}}/*** 递增** @param key   键* @param delta 要增加几(大于0)* @return Long*/public Long incr(String key, Long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/*** 递减** @param key   键* @param delta 要减少几(小于0)* @return Long*/public Long decr(String key, Long delta) {if (delta < 0) {throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}/*** HashGet** @param key  键 不能为 null* @param item 项 不能为 null* @return 值*/public Object hget(String key, String item) {return redisTemplate.opsForHash().get(key, item);}/*** 获取 hashKey对应的所有键值** @param key 键* @return 对应的多个键值*/public Map<Object, Object> hmget(String key) {return redisTemplate.opsForHash().entries(key);}/*** HashSet** @param key 键* @param map 对应多个键值* @return true 成功 false 失败*/public Boolean hmset(String key, Map<String, Object> map) {try {redisTemplate.opsForHash().putAll(key, map);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** HashSet 并设置时间** @param key  键* @param map  对应多个键值* @param time 时间(秒)* @return true成功 false失败*/public Boolean hmset(String key, Map<String, Object> map, Long time) {try {redisTemplate.opsForHash().putAll(key, map);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 向一张hash表中放入数据,如果不存在将创建** @param key   键* @param item  项* @param value 值* @return true 成功 false失败*/public Boolean hset(String key, String item, Object value) {try {redisTemplate.opsForHash().put(key, item, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 向一张hash表中放入数据,如果不存在将创建** @param key   键* @param item  项* @param value 值* @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间* @return true 成功 false失败*/public Boolean hset(String key, String item, Object value, Long time) {try {redisTemplate.opsForHash().put(key, item, value);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除hash表中的值** @param key  键 不能为 null* @param item 项 可以使多个不能为 null*/public void hdel(String key, Object... item) {redisTemplate.opsForHash().delete(key, item);}/*** 判断hash表中是否有该项的值** @param key  键 不能为 null* @param item 项 不能为 null* @return true 存在 false不存在*/public Boolean hHasKey(String key, String item) {return redisTemplate.opsForHash().hasKey(key, item);}/*** hash递增 如果不存在,就会创建一个 并把新增后的值返回** @param key  键* @param item 项* @param by   要增加几(大于0)* @return Double*/public Double hincr(String key, String item, Double by) {return redisTemplate.opsForHash().increment(key, item, by);}/*** hash递减** @param key  键* @param item 项* @param by   要减少记(小于0)* @return Double*/public Double hdecr(String key, String item, Double by) {return redisTemplate.opsForHash().increment(key, item, -by);}/*** 根据 key获取 Set中的所有值** @param key 键* @return Set*/public Set<Object> sGet(String key) {try {return redisTemplate.opsForSet().members(key);} catch (Exception e) {e.printStackTrace();return null;}}/*** 根据value从一个set中查询,是否存在** @param key   键* @param value 值* @return true 存在 false不存在*/public Boolean sHasKey(String key, Object value) {try {return redisTemplate.opsForSet().isMember(key, value);} catch (Exception e) {e.printStackTrace();return false;}}/*** 将数据放入set缓存** @param key    键* @param values 值 可以是多个* @return 成功个数*/public Long sSet(String key, Object... values) {try {return redisTemplate.opsForSet().add(key, values);} catch (Exception e) {e.printStackTrace();return 0L;}}/*** 将set数据放入缓存** @param key    键* @param time   时间(秒)* @param values 值 可以是多个* @return 成功个数*/public Long sSetAndTime(String key, Long time, Object... values) {try {Long count = redisTemplate.opsForSet().add(key, values);if (time > 0)expire(key, time);return count;} catch (Exception e) {e.printStackTrace();return 0L;}}/*** 获取set缓存的长度** @param key 键* @return Long*/public Long sGetSetSize(String key) {try {return redisTemplate.opsForSet().size(key);} catch (Exception e) {e.printStackTrace();return 0L;}}/*** 移除值为value的** @param key    键* @param values 值 可以是多个* @return 移除的个数*/public Long setRemove(String key, Object... values) {try {return redisTemplate.opsForSet().remove(key, values);} catch (Exception e) {e.printStackTrace();return 0L;}}/*** 获取list缓存的内容** @param key   键* @param start 开始* @param end   结束 0 到 -1代表所有值* @return List*/public List<Object> lGet(String key, Long start, Long end) {try {return redisTemplate.opsForList().range(key, start, end);} catch (Exception e) {e.printStackTrace();return null;}}/*** 获取list缓存的长度** @param key 键* @return Long*/public Long lGetListSize(String key) {try {return redisTemplate.opsForList().size(key);} catch (Exception e) {e.printStackTrace();return 0L;}}/*** 通过索引 获取list中的值** @param key   键* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;*              index<0时,-1,表尾,-2倒数第二个元素,依次类推* @return Object*/public Object lGetIndex(String key, Long index) {try {return redisTemplate.opsForList().index(key, index);} catch (Exception e) {e.printStackTrace();return null;}}/*** 将list放入缓存** @param key   键* @param value 值* @return Boolean*/public Boolean lSet(String key, Object value) {try {redisTemplate.opsForList().rightPush(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key   键* @param value 值* @param time  时间(秒)* @return Boolean*/public Boolean lSet(String key, Object value, Long time) {try {redisTemplate.opsForList().rightPush(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key   键* @param value 值* @return Boolean*/public Boolean lSet(String key, List<Object> value) {try {redisTemplate.opsForList().rightPushAll(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key   键* @param value 值* @param time  时间(秒)* @return Boolean*/public Boolean lSet(String key, List<Object> value, Long time) {try {redisTemplate.opsForList().rightPushAll(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据索引修改list中的某条数据** @param key   键* @param index 索引* @param value 值* @return Boolean*/public Boolean lUpdateIndex(String key, Long index, Object value) {try {redisTemplate.opsForList().set(key, index, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 移除N个值为value** @param key   键* @param count 移除多少个* @param value 值* @return 移除的个数*/public Long lRemove(String key, Long count, Object value) {try {return redisTemplate.opsForList().remove(key, count, value);} catch (Exception e) {e.printStackTrace();return 0L;}}
}

4.测试

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import com.hitoo.redis.service.RedisService;/** redis service使用方法*/
@RestController
public class RedisTestController {@Autowiredprivate RedisService redisService;@RequestMapping("/storeToRedis")public String storeToRedis(String id){redisService.set("id", id);return "缓存成功";}@RequestMapping("/getFromRedis")public Object getFromRedis(String key){return redisService.get(key);}
}

代码来源于码云的一个博客,找不到链接了......

spring-boot系列8:集成redis相关推荐

  1. 搞懂分布式技术14:Spring Boot使用注解集成Redis缓存

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/a724888/article/details/80785403 为了提高性能,减少数据库的压力,使用 ...

  2. 超完整!Springboot整合redis集群(Sentine),spring boot自动配置集成redis集群(Sentine)

    1.添加maven依赖 注意maven版本依赖,版本要相互匹配,如不知道如何查看相对应的版本时,可进入博主主页查看博主上一篇博文. <parent><groupId>org.s ...

  3. Spring Boot系列——7步集成RabbitMQ

    RabbitMQ是一种我们经常使用的消息中间件,通过RabbitMQ可以帮助我们实现异步.削峰的目的. 今天这篇,我们来看看Spring Boot是如何集成RabbitMQ,发送消息和消费消息的.同时 ...

  4. Spring Boot 极简集成 Shiro

    点击关注公众号,Java干货及时送达 1. 前言 Apache Shiro是一个功能强大且易于使用的Java安全框架,提供了认证,授权,加密,和会话管理. Shiro有三大核心组件: Subject: ...

  5. 国内最全的Spring Boot系列之三

    历史文章 <国内最全的Spring Boot系列之一> <国内最全的Spring Boot系列之二> 马上要过年了,作者要回家好好休息一下了,吃饱喝足,明年继续.在此和大家拜个 ...

  6. 国内最全的Spring Boot系列之二

    历史文章 <国内最全的Spring Boot系列之一> 视频&交流平台 SpringBoot视频:http://t.cn/R3QepWG Spring Cloud视频:http:/ ...

  7. 电子商务商城源码 Spring Cloud、Spring Boot、Mybatis、Redis

    1. 涉及平台 Spring Cloud.Spring Boot.Mybatis.Redis 2. 核心架构 Spring Cloud.Spring Boot.Mybatis.Redis 3. 前端框 ...

  8. Spring Boot 系列(八)@ControllerAdvice 拦截异常并统一处理

    Spring Boot 系列(八)@ControllerAdvice 拦截异常并统一处理 参考文章: (1)Spring Boot 系列(八)@ControllerAdvice 拦截异常并统一处理 ( ...

  9. 【小马哥】Spring Boot系列讲座

    这里推荐一个不错的Spring Boot系列讲座,讲师简介如下: 小马哥,阿里巴巴技术专家,从事十余年Java EE 开发,国内微服务技术讲师.目前主要负责微服务技术推广.架构设计.基础设施.迁移等. ...

  10. Spring Boot最新版集成邮件发送功能大全

    Spring Boot最新版集成邮件发送功能大全 前言 一.开启SMTP服务并获取授权码 二.创建Spring Boot项目 1.配置邮箱基本信息: 2.简单邮件发送: 3.发送带附件的邮件: 5.使 ...

最新文章

  1. pfSense book之2.4安装指南
  2. pocoserver无限重启_poco相机老版本
  3. hibernate之关联关系(一对多)
  4. ABAP选择屏幕建议
  5. LibreOffice的使用技巧
  6. linux wsgi,linux中wsgi的详解(企业级)
  7. Unity接入腾讯云
  8. Qt-设置completer下拉框样式
  9. 《自拍教程74》Python 假装企业微信电脑在线并定时关机,骗老板的好方法!
  10. Python少儿编程入门篇(1)基本数据类型
  11. vps部署ssl,让域名可以https访问的最简单的办法 ssl无法ie访问 https在ie访问报错的处理办法
  12. SATA,SAS,SSD 读写性能测试结果
  13. 使用 Illustrator 中组合形状的方法详解
  14. 2020年Gartner新兴技术成熟度曲线,AI持续增强
  15. 物体尺寸测量-matlab
  16. 计算机网络 | 思科网络 | 什么是DHCPv4
  17. Java配置文件学习
  18. 微信群打卡小程序_微信打卡小程序上线,你会用吗?
  19. 编译filament
  20. 常见服务器返回状态码

热门文章

  1. CV8 OpenCV环境下实现大津算法
  2. 神器 Codelf !
  3. curl怎么输出赋值_触摸屏与PLC通讯不上?老师告诉你怎么办
  4. ESRI白皮书——ESRI Shapefile 技术描述
  5. windows下用BOSH lite方式在单个VM中安装Cloud Foundry2.x
  6. 中兴阅读,打造专业的企业移动阅读服务
  7. 区块链的一些Api接口
  8. Spring Security和OpenID Connect
  9. 有红、黄、绿三种颜色的球,其中红球 3 个, 黄球 3 个,绿球 6 个。先将这 12 个球混合放在一个盒子中,从中任意摸出 8 个球,编程计算摸出球的各种颜色搭配。1. 输出情况总数;2.输出摸取情
  10. intrusive_ptr