Redis 以JSON格式存储对象

xiaoxiao2021-02-28  22

redis配置

# Redis settings redis.host=192.168.0.106 redis.port=6379 #redis.pass=password redis.dbIndex=0 redis.expiration=3000 redis.maxIdle=300 redis.maxActive=600 redis.maxWait=1000 redis.testOnBorrow=true

spring配置文件

<!-- redis config start --> <!-- 配置JedisPoolConfig实例 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="maxTotal" value="${redis.maxActive}" /> <property name="maxWaitMillis" value="${redis.maxWait}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}" /> </bean> <!-- 配置JedisConnectionFactory --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}" /> <property name="port" value="${redis.port}" /> <!-- <property name="password" value="${redis.pass}" /> --> <property name="database" value="${redis.dbIndex}" /> <property name="poolConfig" ref="poolConfig" /> </bean> <!-- 配置RedisTemplate --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory" /> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"></bean> </property> </bean> <bean id="redisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean> <!-- 配置RedisCacheManager --> <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg name="redisOperations" ref="redisTemplate" /> <property name="defaultExpiration" value="${redis.expiration}" /> </bean>在于 <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>

这个是让redis的键默认是String格式,

<property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"></bean> </property>

这个是让redis的值是自动json格式,如果不是json格式,则是字符串

这样用spring-redis的模版类就可以存对象存为json

转载请注明原文地址: https://www.6miu.com/read-2630289.html

最新回复(0)