1. 程式人生 > >ValueOperations的increment方法ERR value is not an integer or out of range錯誤解釋

ValueOperations的increment方法ERR value is not an integer or out of range錯誤解釋

最近在開發中,使用Redis來實現資料點選量的統計儲存功能。為什麼使用Redis?點選量之類的功能,需要頻繁觸發更新操作,而且高併發訪問時,還需要考慮操作衝突導致資料不一致的問題。而Redis是記憶體型儲存,相比關係型資料庫,操作更快,避免了頻繁的檔案寫操作。更重要的是,Redis中有個INCR和INCRBY命令,都可以實現值遞增的原子性操作,方便了解決了高併發時的衝突問題。
Redis手冊中的命令說明很詳盡,還有Redis中文命令參考的網站可供使用,在此感謝無私的翻譯人員。如下:

Redis中文參考手冊
sdr中針對redis的命令,一一提供了對應的方法可供使用,結合redis命令參考sdr的api,很容易上手。但唯一不足地是,sdr提供的api太簡略了,只提供了函式和引數,引數的說明、返回值的說明、異常情況的說明統統沒有,這個只能自己在實踐的過程中用程式碼來認知了。
sdr中提供了一個ValueOperations的介面來針對Redis中的Key-Value的命令操作。通過粗略追蹤原始碼的手段,可以大概瞭解到,sdr框架操作Redis的實質,是和Redis服務通訊,告知Redis服務執行指定的命令。ValueOperations中有increment方法,本質上是向Redis服務傳送的INCRBY命令。當然要實現點選量遞增的功能,需要使用ValueOperations的increment方法。
Redis採用Key-Value的格式實現了多種結構的資料,例如List、Set等。但Redis中的Key和Value儲存的都是字串,而Java是面向物件的語言,大部分情況下操作資料也都是物件,那麼Java與Redis的結合手段自然是序列化了。sdr提供了豐富的序列化策略,所以在配置sdr時,可以顯示地指定Key和Value的序列化器,如下程式碼所示。這部分不瞭解的同志可以搜尋相關的內容去了解,這裡不再做過多說明。

<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"
/> </property> </bean>

如果沒有顯示指定Key或Value的序列化器,預設採用JdkSerializationRedisSerializer。StringRedisSerializer將資料儲存為正常的字串,而且JdkSerializationRedisSerializer則是將資料儲存為一串序列字串,還需通過反序列化才能得到正常的字串。

當在使用ValueOperations之類的介面時,值得注意的是,介面是使用泛型的,如ValueOperations

<bean id="redisTemplate" class
="org.springframework.data.redis.core.RedisTemplate" p:connectionFactory-ref="jedisConnectionFactory"> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> </property> </bean>
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"           p:connectionFactory-ref="jedisConnectionFactory">         <property name="keySerializer">             <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />         </property>         <property name="valueSerializer">             <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />         </property>     </bean>