springboot+redis整合
2019-08-07 15:20
1021 查看
版权声明:署名,允许他人基于本文进行创作,且必须基于与原先许可协议相同的许可协议分发本文 (Creative Commons)
前言
趁项目空余时间,总结一下springboot与redis整合的相关注意事项和踩过的坑。
Redis简介
Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库。Redis 与其他 key - value 缓存产品有以下三个特点:
1.Redis支持数据的持久化,可以将内存中的数据保存在磁盘中,重启的时候可以再次加载进行使用。
2.Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存储。
3.Redis支持数据的备份,即master-slave模式的数据备份。
Redis 优势:
1.性能极高 – Redis能读的速度是110000次/s,写的速度是81000次/s 。
2.丰富的数据类型 – Redis支持二进制案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 数据类型操作。
3.原子 – Redis的所有操作都是原子性的,意思就是要么成功执行要么失败完全不执行。单个操作是原子性的。多个操作也支持事务,即原子性,通过MULTI和EXEC指令包起来。丰富的特性 – Redis还支持 publish/subscribe, 通知, key 过期等等特性。
pom文件
// redis包 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
yml文件中redis配置
redis: database: 3 # Redis数据库索引(默认为0) host: 192.168.75109 #(改成自己想连接的redis地址) # Redis服务器地址 port: 6379 # Redis服务器连接端口 password: 123456 # Redis服务器连接密码(默认为空) pool: max-active: 1000 # 连接池最大连接数(使用负值表示没有限制) max-idle: 10 # 连接池中的最大空闲连接 max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) min-idle: 0 # 连接池中的最小空闲连接 timeout: 5000 # 连接超时时间(毫秒)
redis配置文件
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.listener.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.stereotype.Component; @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Bean public KeyGenerator keyGenerator() { return (target, method, params) -> { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : params) { sb.append(obj.toString()); } return sb.toString(); }; } @SuppressWarnings("rawtypes") @Bean public CacheManager cacheManager(RedisTemplate redisTemplate) { RedisCacheManager rcm = new RedisCacheManager(redisTemplate); //设置缓存过期时间 rcm.setDefaultExpiration(60);//秒 return rcm; } @Bean public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); template.afterPropertiesSet(); return template; } @Bean public RedisTemplate<String, String> redisJacksonTemplate(RedisConnectionFactory factory) { StringRedisTemplate template = new StringRedisTemplate(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); template.setValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } //=====下面两个bean是订阅队列的写法,只是个例子,可以根据具体需求编写===== @Bean RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer(); container.setConnectionFactory(connectionFactory); //订阅了一个叫chat 的通道 container.addMessageListener(listenerAdapter, new PatternTopic("chat")); //这个container 可以添加多个 messageListener return container; } @Bean MessageListenerAdapter listenerAdapter(MessageReceiver receiver) { //这个地方 是给messageListenerAdapter 传入一个消息接受的处理器,利用反射的方法调用“receiveMessage” //也有好几个重载方法,这边默认调用处理器的方法 叫handleMessage 可以自己到源码里面看 return new MessageListenerAdapter(receiver, "receiveMessage"); } /** * redis 消息处理器 */ @Component public class MessageReceiver { /** * 接收消息的方法 */ public void receiveMessage(String message) { System.out.println(message); } } //=====上面两个bean是订阅队列的写法,只是个例子,可以根据具体需求编写===== }
@Service public class StudentServiceImpl { @Autowired private StudentRepository studentRepository; @Autowired private RedisTemplate redisTemplate; public void set(Student student) { String key = CacheUtil.getStudentKey(student.getId()); ObjectMapper objectMapper = new ObjectMapper(); try { // 1.1以字符串形式存到redis中 redisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(student)); // 1.2过期时间 -- 键 时间 单位 (10分钟过期) redisTemplate.expire(key, 10, TimeUnit.MINUTES); // 1.3redis中获取学生信息 Object studentInfo = redisTemplate.opsForValue().get(key); // 2.1以hash的形式存到redis中 Map<String, Object> student1 = new HashMap<>(); student1.put("id", student.getId()); student1.put("age", student.getAge()); student1.put("name", student.getName()); redisTemplate.opsForHash().putAll(key, student1); redisTemplate.expire(key, 10, TimeUnit.MINUTES); // 2.2从redis中获取学生信息 Map<String, Object> stu = redisTemplate.opsForHash().entries(key); } catch (JsonProcessingException e) { e.printStackTrace(); } } }
util工具类
public class CacheUtil { private static final String PREFIX = "student:"; /** * 用学生信息 */ public static String getStudentKey(Integer studentId) { return PREFIX + "student:" + studentId; } }
相关文章推荐
- SpringBoot 整合 Redis 的简单案例
- Spring Boot + MyBatis + Redis整合小案例
- Spring Boot+Shiro+Redis(redisson)整合时,采用内嵌tomcat启动错误原因分析
- Springboot+redis 整合
- spring boot 1.5.9 整合redis
- SpringBoot开发详解(十一) -- Redis在SpringBoot中的整合
- spring boot redis整合
- spring boot shiro redis整合
- Spring Boot整合Redis
- springboot整合redis进行数据操作(一)
- SpringBoot整合Redis
- springboot整合Redis
- spring boot 2.x 系列 —— spring boot 整合 redis
- Spring Boot 2.X 学习日记——整合redis
- springboot整合dubbo,redis,jwt,atomikos
- springboot 简单查询 整合redis
- [置顶] 安装docker-compose 并且发布spring boot整合redis做访问计数demo
- Spring boot整合redis
- Docker 部署 SpringBoot 项目整合 Redis 镜像做访问计数Demo
- Docker 部署 SpringBoot 项目整合 Redis 镜像做访问计数Demo