在前面的例子中加入事务
package com.redis.DAO;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import com.redis.bean.UserBean;
import com.redis.storage.RedisPool;
public class UserDAO {
private static final String U_UID = "uid";
private static final String U_KEY = "gen_sn";
private static final String U_NAME = "name";
private static final String U_PROFILE_PRE = "pr:";
public UserBean getUserFromRedis(String genSN) throws Exception {
UserBean userBean = null;
Jedis jedis = null;
try {
jedis = RedisPool.getInstance().getConnection();
Map<String, String> userProfile = null;
userProfile = jedis.hgetAll(U_PROFILE_PRE + genSN);
if (null != userProfile && userProfile.size() != 0) {
userBean = new UserBean();
userBean.setUid(Long.parseLong(userProfile.get(U_UID)));
userBean.setKey(userProfile.get(U_KEY));
userBean.setName(userProfile.get(U_NAME));
}
} catch (NumberFormatException e) {
throw new Exception(e);
} finally {
RedisPool.getInstance().releaseConnetion(jedis);
}
return userBean;
}
@SuppressWarnings("null")
public void addUserIntoRedis(UserBean userBean) throws Exception {
Jedis jedis = null;
Transaction transaction=null;
try {
jedis = RedisPool.getInstance().getConnection();
transaction = jedis.multi();
HashMap<String, String> profileMap = new HashMap<String, String>();
profileMap.put(U_UID, Long.toString(userBean.getUid()));
if (userBean.getKey() != null) {
profileMap.put(U_KEY, userBean.getKey());
}
if (userBean.getName() != null) {
profileMap.put(U_NAME, userBean.getName());
}
// 放入整个map
transaction.hmset(U_PROFILE_PRE + userBean.getKey(), profileMap);
//50%几率抛异常
Random r=new Random();
int i=r.nextInt(2);
if(i==0) {
String sss=null;
System.out.println(sss.length());
}
transaction.exec();
} catch (Exception e) {
transaction.discard();
throw new Exception(e);
} finally {
RedisPool.getInstance().releaseConnetion(jedis);
}
}
}
package com.redis.service;
import com.redis.DAO.UserDAO;
import com.redis.bean.UserBean;
import com.redis.storage.RedisPool;
public class Main {
public static void main(String[] args) {
RedisPool.getInstance().Init();
UserDAO dao=new UserDAO();
UserBean user=new UserBean();
user.setKey("test"); //唯一标识
user.setUid(1000);
user.setName("小高");
try {
dao.addUserIntoRedis(user);
} catch (Exception e) {
System.out.println(user+" 插入失败");
}
System.out.println("-----------------------6-----------------");
UserBean result=null;
try {
result = dao.getUserFromRedis("test");
} catch (Exception e) {
System.out.println(user+" 获取失败");
}
System.out.println(result.getUid());
System.out.println(result.getName());
}
}