Spring-data-redis: 事務與pipeline
-
本文主要展示如何使用spring-data-redis編寫事務和pipeline:
1.配置檔案:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" default-autowire="byName"
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxActive" value="32"></property> <property name="maxIdle" value="6"></property> <property name="maxWait" value="15000"></property> <property name="minEvictableIdleTimeMillis" value="300000"></property> <property name="numTestsPerEvictionRun" value="3"></property> <property name="timeBetweenEvictionRunsMillis" value="60000"></property> <property name="whenExhaustedAction" value="1"></property> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="poolConfig" ref="jedisPoolConfig"></property> <property name="hostName" value="127.0.0.1"></property> <property name="port" value="6379"></property> <property name="password" value="0123456"></property> <property name="timeout" value="15000"></property> <property name="usePool" value="true"></property> </bean> <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"></property> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> </bean> </beans>2. 程式例項:
package com.sample.redis.sdr; public class RedisClientTest { //private JsonRedisSeriaziler seriaziler; private RedisTemplate redisTemplate; public void setRedisTemplate(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public void valueOperationSample(){ ValueOperations<String, User> valueOper = redisTemplate.opsForValue(); User suser = new User(1,"zhangsan",12); valueOper.set("user:" + suser.getId(),suser); System.out.println(valueOper.get("user:" + suser.getId()).getName()); } public void listOperationSample(){ User suser = new User(1,"zhangsan",12); ListOperations<String, User> listOper = redisTemplate.opsForList(); listOper.leftPush("user:list", suser);//lpush,head listOper.rightPush("user:list", suser);//rpush,tail }
com.sample.redis.sdr; public class RedisClientTest { //private JsonRedisSeriaziler seriaziler; private RedisTemplate redisTemplate; public void setRedisTemplate(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public void valueOperationSample(){ ValueOperations<String, User> valueOper = redisTemplate.opsForValue(); User suser = new User(1,"zhangsan",12); valueOper.set("user:" + suser.getId(),suser); System.out.println(valueOper.get("user:" + suser.getId()).getName()); } public void listOperationSample(){ User suser = new User(1,"zhangsan",12); ListOperations<String, User> listOper = redisTemplate.opsForList(); listOper.leftPush("user:list", suser);//lpush,head listOper.rightPush("user:list", suser);//rpush,tail }public void boundValueOperationSample(){ User suser = new User(1,"zhangsan",12); BoundValueOperations<String, User> bvo = redisTemplate.boundValueOps("user:" + suser.getId()); bvo.set(suser); bvo.expire(60, TimeUnit.MINUTES); } /** * 非連線池環境下,事務操作;對於sdr而言,每次操作(例如,get,set)都有會從pool中獲取connection; * 因此在連線池環境下,使用事務需要注意。 */ public void txUnusedPoolSample(){ User suser = new User(1,"zhangsan",12); redisTemplate.watch("user:" + suser.getId()); redisTemplate.multi(); ValueOperations<String, User> tvo = redisTemplate.opsForValue(); tvo.set("user:" + suser.getId(), suser); redisTemplate.exec(); } /** * 在連線池環境中,需要藉助sessionCallback來繫結connection */ public void txUsedPoolSample(){ SessionCallback<User> sessionCallback = new SessionCallback<User>() { @Override public User execute(RedisOperations operations) throws DataAccessException { operations.multi(); User user = new User(2,"lisi",32); String key = "user:" + user.getId(); BoundValueOperations<String, User> oper = operations.boundValueOps(key); oper.set(user); oper.expire(60, TimeUnit.MINUTES); operations.exec(); return user; } }; redisTemplate.execute(sessionCallback); } /** * pipeline : 1,正確使用方式 */ public void pipelineSample(){ final byte[] rawKey = redisTemplate.getKeySerializer().serialize("user_total"); //pipeline RedisCallback<List<Object>> pipelineCallback = new RedisCallback<List<Object>>() { @Override public List<Object> doInRedis(RedisConnection connection) throws DataAccessException { connection.openPipeline(); connection.incr(rawKey); connection.incr(rawKey); return connection.closePipeline(); } }; List<Object> results = (List<Object>)redisTemplate.execute(pipelineCallback); for(Object item : results){ System.out.println(item.toString()); } } //pipeline:備用方式 public void pipelineSampleX(){ byte[] rawKey = redisTemplate.getKeySerializer().serialize("user_total"); RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); RedisConnection redisConnection = factory.getConnection(); List<Object> results; try{ redisConnection.openPipeline(); redisConnection.incr(rawKey); results = redisConnection.closePipeline(); }finally{ RedisConnectionUtils.releaseConnection(redisConnection, factory); } if(results == null){ return; } for(Object item : results){ System.out.println(item.toString()); } } }
public void boundValueOperationSample(){ User suser = new User(1,"zhangsan",12); BoundValueOperations<String, User> bvo = redisTemplate.boundValueOps("user:" + suser.getId()); bvo.set(suser); bvo.expire(60, TimeUnit.MINUTES); } /** * 非連線池環境下,事務操作;對於sdr而言,每次操作(例如,get,set)都有會從pool中獲取connection; * 因此在連線池環境下,使用事務需要注意。 */ public void txUnusedPoolSample(){ User suser = new User(1,"zhangsan",12); redisTemplate.watch("user:" + suser.getId()); redisTemplate.multi(); ValueOperations<String, User> tvo = redisTemplate.opsForValue(); tvo.set("user:" + suser.getId(), suser); redisTemplate.exec(); } /** * 在連線池環境中,需要藉助sessionCallback來繫結connection */ public void txUsedPoolSample(){ SessionCallback<User> sessionCallback = new SessionCallback<User>() { @Override public User execute(RedisOperations operations) throws DataAccessException { operations.multi(); User user = new User(2,"lisi",32); String key = "user:" + user.getId(); BoundValueOperations<String, User> oper = operations.boundValueOps(key); oper.set(user); oper.expire(60, TimeUnit.MINUTES); operations.exec(); return user; } }; redisTemplate.execute(sessionCallback); } /** * pipeline : 1,正確使用方式 */ public void pipelineSample(){ final byte[] rawKey = redisTemplate.getKeySerializer().serialize("user_total"); //pipeline RedisCallback<List<Object>> pipelineCallback = new RedisCallback<List<Object>>() { @Override public List<Object> doInRedis(RedisConnection connection) throws DataAccessException { connection.openPipeline(); connection.incr(rawKey); connection.incr(rawKey); return connection.closePipeline(); } }; List<Object> results = (List<Object>)redisTemplate.execute(pipelineCallback); for(Object item : results){ System.out.println(item.toString()); } } //pipeline:備用方式 public void pipelineSampleX(){ byte[] rawKey = redisTemplate.getKeySerializer().serialize("user_total"); RedisConnectionFactory factory = redisTemplate.getConnectionFactory(); RedisConnection redisConnection = factory.getConnection(); List<Object> results; try{ redisConnection.openPipeline(); redisConnection.incr(rawKey); results = redisConnection.closePipeline(); }finally{ RedisConnectionUtils.releaseConnection(redisConnection, factory); } if(results == null){ return; } for(Object item : results){ System.out.println(item.toString()); } } }
public void boundValueOperationSample(){
User suser = new User(1,"zhangsan",12);
BoundValueOperations<String, User> bvo = redisTemplate.boundValueOps("user:" + suser.getId());
bvo.set(suser);
bvo.expire(60, TimeUnit.MINUTES);
}
/**
* 非連線池環境下,事務操作;對於sdr而言,每次操作(例如,get,set)都有會從pool中獲取connection;
* 因此在連線池環境下,使用事務需要注意。
*/
public void txUnusedPoolSample(){
User suser = new User(1,"zhangsan",12);
redisTemplate.watch("user:" + suser.getId());
redisTemplate.multi();
ValueOperations<String, User> tvo = redisTemplate.opsForValue();
tvo.set("user:" + suser.getId(), suser);
redisTemplate.exec();
}
/**
* 在連線池環境中,需要藉助sessionCallback來繫結connection
*/
public void txUsedPoolSample(){
SessionCallback<User> sessionCallback = new SessionCallback<User>() {
@Override
public User execute(RedisOperations operations) throws DataAccessException {
operations.multi();
User user = new User(2,"lisi",32);
String key = "user:" + user.getId();
BoundValueOperations<String, User> oper = operations.boundValueOps(key);
oper.set(user);
oper.expire(60, TimeUnit.MINUTES);
operations.exec();
return user;
}
};
redisTemplate.execute(sessionCallback);
}
/**
* pipeline : 1,正確使用方式
*/
public void pipelineSample(){
final byte[] rawKey = redisTemplate.getKeySerializer().serialize("user_total");
//pipeline
RedisCallback<List<Object>> pipelineCallback = new RedisCallback<List<Object>>() {
@Override
public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
connection.openPipeline();
connection.incr(rawKey);
connection.incr(rawKey);
return connection.closePipeline();
}
};
List<Object> results = (List<Object>)redisTemplate.execute(pipelineCallback);
for(Object item : results){
System.out.println(item.toString());
}
}
//pipeline:備用方式
public void pipelineSampleX(){
byte[] rawKey = redisTemplate.getKeySerializer().serialize("user_total");
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection redisConnection = factory.getConnection();
List<Object> results;
try{
redisConnection.openPipeline();
redisConnection.incr(rawKey);
results = redisConnection.closePipeline();
}finally{
RedisConnectionUtils.releaseConnection(redisConnection, factory);
}
if(results == null){
return;
}
for(Object item : results){
System.out.println(item.toString());
}
}
}
public void boundValueOperationSample(){
User suser = new User(1,"zhangsan",12);
BoundValueOperations<String, User> bvo = redisTemplate.boundValueOps("user:" + suser.getId());
bvo.set(suser);
bvo.expire(60, TimeUnit.MINUTES);
}
/**
* 非連線池環境下,事務操作;對於sdr而言,每次操作(例如,get,set)都有會從pool中獲取connection;
* 因此在連線池環境下,使用事務需要注意。
*/
public void txUnusedPoolSample(){
User suser = new User(1,"zhangsan",12);
redisTemplate.watch("user:" + suser.getId());
redisTemplate.multi();
ValueOperations<String, User> tvo = redisTemplate.opsForValue();
tvo.set("user:" + suser.getId(), suser);
redisTemplate.exec();
}
/**
* 在連線池環境中,需要藉助sessionCallback來繫結connection
*/
public void txUsedPoolSample(){
SessionCallback<User> sessionCallback = new SessionCallback<User>() {
@Override
public User execute(RedisOperations operations) throws DataAccessException {
operations.multi();
User user = new User(2,"lisi",32);
String key = "user:" + user.getId();
BoundValueOperations<String, User> oper = operations.boundValueOps(key);
oper.set(user);
oper.expire(60, TimeUnit.MINUTES);
operations.exec();
return user;
}
};
redisTemplate.execute(sessionCallback);
}
/**
* pipeline : 1,正確使用方式
*/
public void pipelineSample(){
final byte[] rawKey = redisTemplate.getKeySerializer().serialize("user_total");
//pipeline
RedisCallback<List<Object>> pipelineCallback = new RedisCallback<List<Object>>() {
@Override
public List<Object> doInRedis(RedisConnection connection) throws DataAccessException {
connection.openPipeline();
connection.incr(rawKey);
connection.incr(rawKey);
return connection.closePipeline();
}
};
List<Object> results = (List<Object>)redisTemplate.execute(pipelineCallback);
for(Object item : results){
System.out.println(item.toString());
}
}
//pipeline:備用方式
public void pipelineSampleX(){
byte[] rawKey = redisTemplate.getKeySerializer().serialize("user_total");
RedisConnectionFactory factory = redisTemplate.getConnectionFactory();
RedisConnection redisConnection = factory.getConnection();
List<Object> results;
try{
redisConnection.openPipeline();
redisConnection.incr(rawKey);
results = redisConnection.closePipeline();
}finally{
RedisConnectionUtils.releaseConnection(redisConnection, factory);
}
if(results == null){
return;
}
for(Object item : results){
System.out.println(item.toString());
}
}
}
相關推薦
Spring-data-redis: 事務與pipeline
本文主要展示如何使用spring-data-redis編寫事務和pipeline: 1.配置檔案: <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http:
Java Spring Data Redis實戰與配置引數詳解 application.properties
Redis作為開源分散式高併發快取,使用範圍非常廣泛,主流網際網路公司幾乎都在使用。 Java Spring Boot 2.0實戰開發Redis快取可以參考下面的步驟,Redis安裝可以直接使用Linux倉庫,特定版本請使用Wget下載安裝。 Java Spring Boot 2.0連線Redis伺服
redis集群 與spring-data-redis 集成
span 版本 生效 pass name 引入 clust clu redis集群 所遇到的坑:必須使用如下的jedis 版本與spring-data-redis 版本,才能夠達到集群效果 。1.7版本以前是不支持集群的 <dependency>
spring-data-redis的事務操作深度解析--原來客戶端庫還可以攢夠了事務命令再發?
一、官方文件 簡單介紹下redis的幾個事務命令: redis事務四大指令: MULTI、EXEC、DISCARD、WATCH。 這四個指令構成了redis事務處理的基礎。 1.MULTI用來組裝一個事務;2.EXEC用來執行一個事務;3.DISCARD用來取消一個事務; 4.WATCH類似於樂觀鎖
SDR(spring.data.redis)與Sentinel高可用叢集Redis客戶端Jedis配置
依賴 <dependency> <groupId>junit</groupId> <artifactId>junit<
redis與spring整合--不使用spring-data-redis
個人感覺如果使用spring-data-redis只作為快取的話有點累贅,所以有了以下方式 之前在網上搜索了一些資料,但是其中的配置總是報錯,原因是JedisShardInfo類缺少相應的構造方法...... 1.redis.xml配置 spring的配置檔案 <?
spring-data-redis使用RedisTemplate模板儲存時鍵值與預設不一致的解決方法
一、背景 最近使用spring-data-redis 和jedis 操作redis時發現儲存在redis中的key不是程式中設定的string值,前面還多出了許多類似\xac\xed\x00\x05t
Spring整合Redis(spring-data-redis)
nds 獲取 可能 div 普通 工具 long red 等待 歷經幾天看了大量的博客資料,差不多算是搞定了,目前只是針對單個數據源,集群暫時沒研究 maven依賴 <properties> <!-- redis 版本 --> &l
Spring集成Redis方案(spring-data-redis)(基於Jedis的單機模式)(待實踐)
packaging 基於 .cn @override time Coding 很好 -o -i 繼上一篇文章http://www.cnblogs.com/EasonJim/p/7625738.html中提到的幾款客戶端,它們基本都能和Spring集成。 下面介紹的是基於S
使用Spring Data Redis操作Redis(單機版)
nec one com list() 研究 enc keys wire 設置ip Jedis是一款Java連接Redis的客戶端,Spring基於Jedis進行了封裝,提供了簡潔的操作Redis的方法。那就是Spring Data Redis。其實後來研究發現,Spring
Spring Boot + spring-data-redis
調用 ons cor spring edi start ota struct out Redis Redis是緩存, 消息隊列, 多種類型的key-value存儲服務. Spring Boot Spring Boot為Lettcue和Jedis客戶端提供自動註入配置
Spring Data Redis入門示例:程序配置(五)
dex port scl lis fault gre source inf 操作 單機配置 redis.properties配置 #redis的服務器地址 redis.host=127.0.0.1 #redis的服務端口 redis.port=6379 #客戶端超時時間
Spring Data Redis整體介紹 (一)
目前 擴展 刪除 依據 實例化 -m doc 不同的 SDR 為什麽使用Spring Data Redis 首先Spring Data Redis 是Spring 框架提供的用於操作Redis的客戶端。 Spring框架是一個全棧Java程序框架,通過DI、AOP和便攜的服
Spring Data Redis入門示例:字符串操作(六)
擴展 clas cal wire 源碼 cnblogs existing pos 模塊 Spring Data Redis對字符串的操作,封裝在了ValueOperations和BoundValueOperations中,在集成好了SPD之後,在需要的地方引入: // 註入
Spring Data Redis入門示例:基於Jedis及底層API (二)
client classpath mode beans -name maven依賴 eas edi log 使用底層API:RedisConnectionFactory和RedisConnection可以直接操作Redis,下面是一個簡單的例子: ### Maven依賴 &
Spring Data Redis入門示例:基於RedisTemplate (三)
gem per 例子 基於 接口 image 安全 redist 工作 使用底層API:RedisConnection操作Redis,需要對數據進行手動轉換(String <---->byte),需要進行多數重復性工作,效率低下;org.springframew
spring data redis 理解
desc template 開啟 利用 one 反序列化 java代碼 native app 前言 Spring Data Redis project,應用了Spring概念來開發使用鍵值形式的數據存儲的解決方案。我們(官方)提供了一個 "template" ,這是一個高級
用redis的scan命令代替keys命令,以及在spring-data-redis中遇到的問題
有一個 arr 問題 public 條件 列表 position cannot clas 摘要 本文主要是介紹使用redis scan命令遇到的一些問題總結,scan命令本身沒有什麽問題,主要是spring-data-redis的問題。 需求 需要遍歷redis中key,找
spring-data-redis時效設置
back fig rgs lis lena substr sync exceptio enum 本人轉自http://hbxflihua.iteye.com/blog/2320584#bc2396403 spring目前在@Cacheable和@CacheEvict等註解上
Spring Data Redis 2.x 中 RedisConfiguration 類的新編寫方法
redis 分享 name pub 名稱 per localhost 端口號 vat 在 Spring Data Redis 1.x 的時候,我們可能會在項目中編寫這樣一個RedisConfig類: @Configuration @EnableCaching public