使用Leopard Redis操做Redis

使用Leopard Redis操做Redis

学习如何在旧项目中使用Leopard Redis。

本指南将引导您完成使用Leopard Redis操做Redis。 java

How to complete this guide

你能够从头开始并完成每个步骤,或者您能够绕过你已经熟悉的基本设置步骤。不管哪一种方式,你最终均可以获得可工做的代码。 redis

一、配置maven依赖

在dao模块的pom.xml加入 spring


<dependencies>
    [...]
    <dependency>
        <groupId>io.leopard.data4j</groupId>
        <artifactId>data4j-redis</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
    [...]
</dependencies>
<repositories>
    <repository>
        <id>leopard-snapshots</id>
        <name>Leopard Snapshots</name>
        <url>http://leopard.io/nexus/content/repositories/snapshots/</url>
    </repository>
</repositories>
若是您是非maven用户,能够经过如下连接下载jar包.
io.leopard.data4j:data4j-redis:0.0.1-SNAPSHOT


二、配置spring

src/main/resources/applicationContext-dao.xml json

<?xml version="1.0" encoding="UTF-8"?>
<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">

	<bean id="userDao" class="io.leopard.guides.dao.UserDao" />

	<bean id="redis" class="io.leopard.data4j.redis.RedisImpl">
		<property name="server" value="112.126.75.27:6311" />
		<property name="maxActive" value="128" />
	</bean>

</beans>


三、使用Redis接口

建立src/main/java/io/leopard/guides/dao/UserDao.java app

package io.leopard.guides.dao;

import io.leopard.burrow.lang.Json;
import io.leopard.data4j.redis.Redis;
import io.leopard.guides.model.User;

import javax.annotation.Resource;

public class UserDao {

	@Resource
	private Redis redis;

	protected String getKey(long uid) {
		return "user:" + uid;
	}

	/**
	 * 添加用户.
	 * 
	 * @param user
	 * @return 添加成功返回true,出错抛异常
	 */
	public boolean add(User user) {
		String key = this.getKey(user.getUid());
		String json = Json.toJson(user);
		this.redis.set(key, json);
		return true;
	}

	/**
	 * 根据uid获取用户信息.
	 * 
	 * @param uid
	 * @return 用户存在则返回用户对象,不存在则返回null.
	 */
	public User get(long uid) {
		String key = this.getKey(uid);
		String json = this.redis.get(key);
		return Json.toObject(json, User.class);
	}

	/**
	 * 删除用户
	 * 
	 * @param uid
	 * @return 成功删除记录就返回true,记录不存在则返回false,出错则抛异常.
	 */
	public boolean delete(long uid) {
		String key = this.getKey(uid);
		Long result = this.redis.del(key);
		return (result != null && result == 1);

	}
}


Json解析模块引入

例子代码中使用到Json类,若是你但愿在项目中使用,须要配置maven依赖 maven


<dependencies>
    [...]
    <dependency>
        <groupId>io.leopard.burrow</groupId>
        <artifactId>burrow-lang</artifactId>
        <version>0.0.5-SNAPSHOT</version>
    </dependency>
    [...]
</dependencies>
若是您是非maven用户,能够经过如下连接下载jar包.
io.leopard.burrow:burrow-lang:0.0.5-SNAPSHOT


了解Leopard更多功能模块,请访问http://leopard.io/ ide

总结

恭喜你!您已经能够在旧项目配置使用Leopard Redis,虽然功能比较简单,你能够在这个基础上扩展出你的业务系统,祝您好运。 学习

相关文章
相关标签/搜索