Nutz对Redis数据库的CRUD操作

最近研究了一下java操作Redis,发现跟操作对象数据库的思路有很大的不同,特别是对Redis的key设计,感觉一时还转不过弯啦,得慢慢练练了,呵呵~~

本文采用了Nutz框架+Jedis客户端,因为Nutz这个国产框架挺不错的,方便、简单、效率高,呵呵,顺便帮它做下广告了。。而Jedis也是Redis官方推荐的Java客户端工具,相对于其它客户端来说比较成熟。

关于这两个技术的使用,请移步官方网站查看。

Nutz框架:http://www.nutzam.com/

Jedis客户端:https://github.com/xetorthio/jedis

--------------------------------------

一个简单的CURD操作,数据表名UserInfo,字段有id,userName,trueName,blogUrl

存储在Redis的key有以下几个:
userinfo:id
userinfo:id:userName
userinfo:id:trueName
userinfo:id:blogUrl
userinfo:nextid    // 保存id的自增值
userinfo:list         // 存放所有id的list,方便列表显示

OK,上代码!!
--------------------------------------
jedis.js 配置连接Redis参数

var ioc = {
	jedisShardInfo : {
		type : "redis.clients.jedis.JedisShardInfo",
		args : [ "127.0.0.1", 6379 ]
	}
};

MainModule.java

package me.gevin;

import me.gevin.module.UserInfoModule;

import org.nutz.mvc.annotation.IocBy;
import org.nutz.mvc.annotation.Modules;
import org.nutz.mvc.annotation.SetupBy;
import org.nutz.mvc.ioc.provider.ComboIocProvider;

/**
 *
 * @author gevin<gevinhjy@gmail.com>(http://gevin.me/)
 *
 */
@Modules(value = { UserInfoModule.class }, scanPackage=true)
@IocBy(type = ComboIocProvider.class, args = {
	"*org.nutz.ioc.loader.json.JsonLoader", "ioc/jedis.js",
	"*org.nutz.ioc.loader.annotation.AnnotationIocLoader", "me.gevin"})
@SetupBy(value = NutzSetup.class)
public class MainModule {}

BaseJedis.java 基类,可在此定义通用方法

package me.gevin;

import org.nutz.ioc.loader.annotation.IocBean;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisShardInfo;

/**
 *
 * @author gevin<gevinhjy@gmail.com>(http://gevin.me/)
 *
 */
@IocBean(name = "jedis", args = { "refer:jedisShardInfo" })
public class BaseJedis extends Jedis {

	private Jedis jedis;

	public BaseJedis(JedisShardInfo shardInfo) {
		super(shardInfo);
		jedis = new Jedis(shardInfo);
	}

	public String incrId(String key) {
		return new Long(jedis.incr(key)).toString();
	}

}

UserInfo.java Model类

package me.gevin.bean;

import lombok.Data;

/**
 *
 * @author gevin<gevinhjy@gmail.com>(http://gevin.me/)
 *
 */
public @Data class UserInfo {

	private String id;
	private String userName;
	private String trueName;
	private String blogUrl;

	public static String id(String id) {
		return "userinfo:" + id;
	}
	public static String userName(String id) {
		return "userinfo:" + id + ":userName";
	}
	public static String trueName(String id) {
		return "userinfo:" + id + ":trueName";
	}
	public static String blogUrl(String id) {
		return "userinfo:" + id + ":blogUrl";
	}
	public static String nextId() {
		return "userinfo:nextId";
	}
	public static String list() {
		return "userinfo:list";
	}
}

BaseModule.java 基类Module

package me.gevin.module;

import java.util.HashMap;
import java.util.Map;

import me.gevin.BaseJedis;

import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.random.StringGenerator;

/**
 *
 * @author gevin<gevinhjy@gmail.com>(http://gevin.me/)
 *
 */
@IocBean
public class BaseModule {

	protected Map<String, Object> data = new HashMap<String, Object>();

	// 定义操作结果字符串
	protected static String ADD_SUCCESS = "addSuccess";
	protected static String ADD_FAILURE = "addFailure";

	protected static String EDIT_SUCCESS = "editSuccess";
	protected static String EDIT_FAILURE = "editFailure";

	protected static String DEL_SUCCESS = "delSuccess";
	protected static String DEL_FAILURE = "delFailure";

	protected static String GET_SUCCESS = "getSuccess";
	protected static String GET_FAILURE = "getFailure";

	protected static String OP_SUCCESS = "opSuccess";
	protected static String OP_FAILURE = "opFailure";

	@Inject(value = "refer:jedis")
	protected BaseJedis jedis;

	/**
	 * 返回错误结果
	 *
	 * @param errorMsg
	 * @param map
	 * @return
	 */
	public Map<String, Object> failure(String errorMsg, Map<String, Object> map) {
		map.put("msg", errorMsg);
		return map;
	}

	/**
	 * 返回成功结果
	 *
	 * @param successMsg
	 * @param map
	 * @return
	 */
	public Map<String, Object> success(String successMsg, Map<String, Object> map) {
		map.put("msg", successMsg);
		return map;
	}

	/**
	 * 返回成功结果
	 *
	 * @param successMsg
	 * @param map
	 * @return
	 */
	public Map<String, Object> success(Map<String, Object> map) {
		return map;
	}
}

UserInfoModule.java CURD操作类

package me.gevin.module;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.gevin.bean.UserInfo;

import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

/**
 *
 * @author gevin(http://gevin.me/)
 *
 */
@IocBean
@At("/userinfo")
public class UserInfoModule extends BaseModule{

	/**
	 * 添加成功
	 *
	 * @param ui
	 * @return
	 */
	@At("/addOk")
	@Ok("jsp:/userinfo/msg")
	public Map addOk(@Param("..") UserInfo ui) {
		try {
			if (ui == null)
				return null;

			String id = jedis.incrId(UserInfo.nextId());
			jedis.rpush(UserInfo.list(), id);

			jedis.set(UserInfo.id(id), id);
			jedis.set(UserInfo.userName(id), ui.getUserName());
			jedis.set(UserInfo.trueName(id), ui.getTrueName());
			jedis.set(UserInfo.blogUrl(id), ui.getBlogUrl());

			return success(ADD_SUCCESS, data);
		} catch (Exception e) {
			e.printStackTrace();
			return failure(ADD_FAILURE, data);
		}
	}

	/**
	 * 跳转到修改页面
	 *
	 * @param id
	 * @return
	 */
	@At("/edit")
	@Ok("jsp:/userinfo/edit")
	public Map edit(@Param("id") String id) {
		try {
			String userName = jedis.get(UserInfo.userName(id));
			String trueName = jedis.get(UserInfo.trueName(id));
			String blogUrl = jedis.get(UserInfo.blogUrl(id));

			UserInfo ui = new UserInfo();
			ui.setId(id);
			ui.setUserName(userName);
			ui.setTrueName(trueName);
			ui.setBlogUrl(blogUrl);

			this.data.put("userInfo", ui);
			return success(data);
		} catch (Exception e) {
			e.printStackTrace();
			return failure(GET_FAILURE, data);
		}
	}

	/**
	 * 修改成功
	 *
	 * @param ui
	 * @return
	 */
	@At("/editOk")
	@Ok("jsp:/userinfo/msg")
	public Map editOk(@Param("..") UserInfo ui) {
		try {
			if (ui == null)
				return null;

			String id = ui.getId();

			jedis.set(UserInfo.id(id), id);
			jedis.set(UserInfo.userName(id), ui.getUserName());
			jedis.set(UserInfo.trueName(id), ui.getTrueName());
			jedis.set(UserInfo.blogUrl(id), ui.getBlogUrl());

			return success(EDIT_SUCCESS, data);
		} catch (Exception e) {
			e.printStackTrace();
			return failure(GET_FAILURE, data);
		}
	}

	/**
	 * 删除成功
	 *
	 * @param id
	 * @return
	 */
	@At("/deleteOk")
	@Ok("jsp:/userinfo/msg")
	public Map deleteOk(@Param("id") String id) {
		try {
			if (Strings.isBlank(id))
				return failure(GET_FAILURE, data);

			if (jedis.get(UserInfo.id(id)) == null)
				return failure(GET_FAILURE, data);

			jedis.del(UserInfo.id(id));
			jedis.del(UserInfo.userName(id));
			jedis.del(UserInfo.trueName(id));
			jedis.del(UserInfo.blogUrl(id));

			// lrem(String key, long count, String value) 从key对应list中删除count个和value相同的元素。count为0时候删除全部
			jedis.lrem(UserInfo.list(), 1, id);

			return success(DEL_SUCCESS, data);
		} catch (Exception e) {
			e.printStackTrace();
			return failure(GET_FAILURE, data);
		}
	}

	/**
	 * 列表
	 *
	 * @return
	 */
	@At("/list")
	@Ok("jsp:/userinfo/list")
	public Map list() {
		try {
			List ids = jedis.lrange(UserInfo.list(), 0, -1);
			List userInfos = new ArrayList(ids.size());
			for (String id : ids) {
				String userName = jedis.get(UserInfo.userName(id));
				String trueName = jedis.get(UserInfo.trueName(id));
				String blogUrl = jedis.get(UserInfo.blogUrl(id));

				UserInfo ui = new UserInfo();
				ui.setId(id);
				ui.setUserName(userName);
				ui.setTrueName(trueName);
				ui.setBlogUrl(blogUrl);
				userInfos.add(ui);
			}

			data.put("userInfos", userInfos);
			return success(data);
		} catch (Exception e) {
			e.printStackTrace();
			data.put("userInfos", null);
			return success(data);
		}
	}
}

list.jsp 显示列表

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<%@ include file="../../include/taglibs.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>列表</title>
<style>
body{ margin:0px; padding:0px; font-size:9pt; }

</style>
</head>

<body>
<br />

<form id="form1" name="form1" method="post" action="addOk.shtml">
  <table width="700" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
      <td width="82" height="28" align="center">用户名:</td>
      <td width="124"><input name="userName" type="text" id="userName" size="14" /></td>
      <td width="79" align="center">真实姓名:</td>
      <td width="127"><input name="trueName" type="text" id="trueName" size="14" /></td>
      <td width="78" align="center">博客地址:</td>
      <td width="210"><input name="blogUrl" type="text" id="blogUrl" size="25" /></td>
    </tr>
    <tr>
      <td height="28" colspan="6" align="center"><input type="submit" name="add" id="add" value="添加" /></td>
    </tr>
  </table>
</form>
<br />
<table width="700" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td width="72" height="28" align="center">序号</td>
    <td width="110" align="center">用户名</td>
    <td width="123" align="center">真实姓名</td>
    <td width="288" align="center">博客地址</td>
    <td width="107" align="center">操作</td>
  </tr>
  <c:forEach var="ui" items="${obj.userInfos}" varStatus="status">
  <tr>
    <td height="28" align="center"><c:out value="${status.count}" /></td>
    <td align="center"><c:out value="${ui.userName}" /></td>
    <td align="center"><c:out value="${ui.trueName}" /></td>
    <td align="center"><c:out value="${ui.blogUrl}" /></td>
    <td align="center"><a href="edit.shtml?id=${ui.id}">修改</a> <a href="deleteOk.shtml?id=${ui.id}" onclick="return(confirm('是否真的要删除此记录?'))">删除</a></td>
  </tr>
  </c:forEach>
</table>
</body>
</html>

edit.jsp 修改界面

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<%@ include file="../../include/taglibs.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>修改</title>
<style>
body{ margin:0px; padding:0px; font-size:9pt; }

</style>
</head>

<body>
<br />
<c:set var="ui" value="${obj.userInfo}" />
<form id="form1" name="form1" method="post" action="editOk.shtml">
<input name="id" type="hidden" value="${ui.id}" />
  <table width="700" border="0" align="center" cellpadding="0" cellspacing="0">
    <tr>
      <td width="82" height="28" align="center">用户名:</td>
      <td width="124"><input name="userName" type="text" id="userName" size="14" value="${ui.userName}" /></td>
      <td width="79" align="center">真实姓名:</td>
      <td width="127"><input name="trueName" type="text" id="trueName" size="14" value="${ui.trueName}" /></td>
      <td width="78" align="center">博客地址:</td>
      <td width="210"><input name="blogUrl" type="text" id="blogUrl" size="25" value="${ui.blogUrl}" /></td>
    </tr>
    <tr>
      <td height="28" colspan="6" align="center"><input type="submit" name="edit" id="edit" value="修改" /></td>
    </tr>
  </table>
</form>
</body>
</html>

运行效果:

本文固定链接: http://gevin.me/400.html | Gevin's Blog

该日志由 admin 于2012年03月21日发表在 Database, Java 分类下, 通告目前不可用,你可以至底部留下评论。
原创文章转载请注明: Nutz对Redis数据库的CRUD操作 | Gevin's Blog
关键字: , ,

Nutz对Redis数据库的CRUD操作:等您坐沙发呢!

发表评论

快捷键:Ctrl+Enter