Spring-boot通过redisTemplate使用redis(无须手动序列化)
转载请注明出处 : Spring-boot通过redisTemplate使用redis(无须手动序列化)
redisTemplate的一些操作可以参考下面俩篇文章
https://www.geek-share.com/detail/2678974822.html
http://www.jianshu.com/p/7bf5dc61ca06
#导入redis依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
#Jackson依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.3.2</version> </dependency>
#配置redis
方式一 redisProperties.yml
spring: redis: database: 0 # Redis数据库索引(默认为0) host: localhost # Redis服务器地址 port: 6379 # Redis服务器连接端口 password: # Redis服务器连接密码(默认为空) timeout: 0 # 连接超时时间(毫秒) pool: max-active: 8 # 连接池最大连接数(使用负值表示没有限制) max-idle: 8 # 连接池中的最大空闲连接 max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) min-idle: 0 # 连接池中的最小空闲连接12345678910111213
方式二 redis.Properties
# Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=localhost # 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=0
#新建处理序列化的类
使redisTemplate无须手动序列化的类,并用jackson替换默认的序列化工具
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; @Configuration public class RedisConfig { /** * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类 * @param redisConnectionFactory * @return */ @Bean public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 使用Jackson2JsonRedisSerialize 替换默认序列化 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); // 设置value的序列化规则和 key的序列化规则 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
User.java实体
package com.biologic.entity; public class User { private String id; private String username; private String password; private String registerTime; private String phone; private String name; private String sex; private String age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getRegisterTime() { return registerTime; } public void setRegisterTime(String registerTime) { this.registerTime = registerTime; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } }
#开始使用
package com.biologic.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.junit4.SpringRunner; import com.biologic.entity.User; @RunWith(SpringRunner.class) @SpringBootTest public class RedisApplicationTests { @Autowired private RedisTemplate<Object, Object> template; @Test public void contextLoads() { User user = new User(); user.setId("1"); user.setName("joe"); user.setPassword("123"); template.opsForValue().set(user.getId()+"",user); //原本opsForValue()是只能操作字符串的.现在就可以操作对象了 User result = (User) template.opsForValue().get(user.getId()+""); System.out.println(result.getId()+" "+result.getName()); } }
输出结果:
1 joe
RedisTemplate中定义了对5种数据结构操作
redisTemplate.opsForValue();//操作字符串 redisTemplate.opsForHash();//操作hash redisTemplate.opsForList();//操作list redisTemplate.opsForSet();//操作set redisTemplate.opsForZSet();//操作有序set
使用:String[] strarrays = new String[]{"strarr1","sgtarr2"}; System.out.println(template.opsForSet().add("setTest", strarrays)); 结果:2 使用:System.out.println(template.opsForSet().size("setTest")); 结果:1
#共享Session-spring-session-data-redis
分布式系统中,sessiong共享有很多的解决方案,其中托管到缓存中应该是最常用的方案之一,
Spring Session官方说明
Spring Session provides an API and implementations for managing a user’s session information.
更多信息参考 Spring Data Redis
如何使用
1、引入依赖
<dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> </dependency>
2、Session配置:
@Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) public class SessionConfig { }
maxInactiveIntervalInSeconds: 设置Session失效时间,使用Redis Session之后,原Boot的server.session.timeout属性不再生效
好了,这样就配置好了,我们来测试一下
3、测试
添加测试方法获取sessionid
@RequestMapping("/uid") String uid(HttpSession session) { UUID uid = (UUID) session.getAttribute("uid"); if (uid == null) { uid = UUID.randomUUID(); } session.setAttribute("uid", uid); return session.getId(); }
登录redis 输入 keys ‘sessions’
t<spring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4 t(spring:session:expirations:1472976480000
其中 1472976480000为失效时间,意思是这个时间后session失效,db031986-8ecc-48d6-b471-b137a3ed6bc4 为sessionId,登录http://localhost:8080/uid 发现会一致,就说明session 已经在redis里面进行有效的管理了。
如何在两台或者多台中共享session
其实就是按照上面的步骤在另一个项目中再次配置一次,启动后自动就进行了session共享。
- Spring-boot通过redisTemplate使用redis(无须手动序列化)
- springboot使用protostuff进行序列化和反序列化整合redis的redisTemplate的各种方法的写法
- Spring boot下配置使用redis--template编码形式
- 深入理解Spring Redis的使用 (二)、RedisTemplate事务支持、序列化
- 深入理解Spring Redis的使用 (二)、RedisTemplate事务支持、序列化
- 深入理解Spring Redis的使用 (二)、RedisTemplate事务支持、序列化
- 深入理解Spring Redis的使用 (二)、RedisTemplate事务支持、序列化
- spring boot中使用resid-RedisTemplate
- Spring boot 使用多个RedisTemplate
- SpringBoot整合redis集群并使用StringRedisTemplate和RedisTemplate简单操作Redis集群
- redis-springboot-redistemplate更改序列化方式
- springboot中使用redis,key序列化问题解决方案
- redis-springboot-redistemplate更改序列化方式
- Redis详解 - SpringBoot整合Redis,RedisTemplate和注解两种方式的使用
- 使用Spring-Data-Redis存储对象(redisTemplate)
- redis 在spring boot工程中的应用(三) 问题发现与解决 :反序列化 报错
- 深入理解Spring Redis的使用 (三)、使用RedisTemplate的操作类访问Redis
- Spring boot 手动配置redis
- springboot 手动集成redis
- springboot与redis使用(1)