1. 程式人生 > >Redis 以JSON格式儲存物件

Redis 以JSON格式儲存物件

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