NutzBook - 集成Redis

NutzBook - 集成Redis

Tags: Nutz

摘要

NutzBook - 集成Redis

添加Redis


        <!-- http://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.8.1</version>
        </dependency>

        <!-- http://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.2</version>
        </dependency>

安装,启动redis

参考 http://javacore.cn/pages/94/install-redis-linux.html

添加redis.js

先添加一个配置文件 resources/custom/redis.properties

redis.host=192.168.1.110
redis.port=6379
redis.timeout=2000
#redis.password=wendal.net
redis.database=0

再添加一个ioc配置文件 conf/ioc/redis.js

var ioc = {
// 参考 https://github.com/xetorthio/jedis/wiki/Getting-started
    jedisPoolConfig : {
        type : "redis.clients.jedis.JedisPoolConfig",
        fields : {
            testWhileIdle : true, // 空闲时测试,免得redis连接空闲时间长了断线
            maxTotal : 100 // 一般都够了吧
        }
    },
    jedisPool : {
        type : "redis.clients.jedis.JedisPool",
        args : [
            {refer : "jedisPoolConfig"},
            // 从配置文件中读取redis服务器信息
            {java : "$conf.get('redis.host', 'localhost')"},
            {java : "$conf.getInt('redis.port', 6379)"},
            {java : "$conf.getInt('redis.timeout', 2000)"},
            {java : "$conf.get('redis.password')"},
            {java : "$conf.getInt('redis.database', 0)"},
        ],
        fields : {},
        events : {
            depose : "destroy" // 关闭应用时必须关掉呢
        }
    }
};

在MainSetup中init方法最后添加测试代码

        JedisPool jedisPool = ioc.get(JedisPool.class);
        try (Jedis jedis = jedisPool.getResource()) { // Java7的语法
            String re = jedis.set("_nutzbook_test_key", "http://javablog.net");
            log.debug("redis say : " + re);
            re = jedis.get("_nutzbook_test_key");
            log.debug("redis say : " + re);
        } finally {
        }

添加redis拦截器

因为JedisPool需要try-finally,所以我们做点改造,用aop的方式演示一种使用方式

package net.javablog.util;


import org.nutz.aop.InterceptorChain;
import org.nutz.aop.MethodInterceptor;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@IocBean(name="redis")
public class RedisInterceptor implements MethodInterceptor {

    @Inject
    JedisPool jedisPool;

    static ThreadLocal<Jedis> TL = new ThreadLocal<Jedis>();

    public void filter(InterceptorChain chain) throws Throwable {
        if (TL.get() != null) {
            chain.doChain();
            return;
        }
        try (Jedis jedis = jedisPool.getResource()) {
            TL.set(jedis);
            chain.doChain();
        } finally{
            TL.remove();
        }
    }

    public static Jedis jedis() {
        return TL.get();
    }
}

这个类的工作方式很简单,就是进入方法之前,取jedis放入ThreadLocal,这样在被拦截的方法内就能通过静态方法 jedis()获取实例,且不需要关心Jedis实例的关闭问题(被拦截的方法执行完毕的时候释放)

添加RedisService

package net.javablog.service;


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

import static net.javablog.util.RedisInterceptor.*; // 静态导入,导入静态方法


@IocBean
public class RedisService {

    @Aop("redis")
    public void set(String key, String val) {
        jedis().set(key, val);
    }

    @Aop("redis") // 加上这个拦截器后jedis()才能返回Jedis实例
    public String get(String key) {
        return jedis().get(key);
    }


}

再在MainSetup中init方法最后添加测试代码

        //AOP方式测试redis
        RedisService redis = ioc.get(RedisService.class);
        redis.set("hi", "刀刀");
        log.debug("redis say again : " + redis.get("hi"));

重启jetty,查看日志