jfinal 使用redis

预设

Ubuntu 上 安装 redis
参见
http://segmentfault.com/a/1190000004109484

概述

jfinal 2.0 中已集成RedisPlugin插件。

RedisPlugin 是支持 Redis 的极速化插件。使用 RedisPlugin 可以极度方便的使用 redis,该插件不仅提供了丰富的 API,而且还同时支持多 redis 服务端。Redis 拥有超高的性能,丰富的数据结构,天然支持数据持久化,是目前应用非常广泛的 nosql 数据库。对于 redis 的有效应用可极大提升系统性能,节省硬件成本。

RedisPlugin

RedisPlugin 是作为 JFinal 的 Plugin 而存在的,所以使用时需要在 JFinalConfig 中配置
RedisPlugin,以下是 RedisPlugin 配置示例代码:

@Override
    public void configPlugin(Plugins plugins){

        //缓存user模块 到 redis
        RedisPlugin userRedis=new RedisPlugin("userCache","172.16.0.102","test123");
        plugins.add(userRedis);
    }

以上代码创建了一个 RedisPlugin 对象userRedis。最先创建的RedisPlugin 对象所持有的 Cache 对象将成为主缓存对象,主缓存对象可通过 Redis.use()直接获取,否则需要提供 cacheName 参数才能获取,例如:Redis.use(“other”)

Redis 与 Cache

Redis 与 Cache 联合起来可以非常方便地使用 Redis 服务,Redis 对象通过 use()方法来获取到 Cache 对象,Cache 对象提供了丰富的 API 用于使用 Redis 服务,下面是具体使用示例:

cache赋值

package controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;

/**
 * Created by renpeng on 2015/12/1.
 */
public class IndexController extends Controller {

    public void index(){
        //获取redis 缓存对象user
        Cache userCache= Redis.use("userCache");
        //在config中最先创建的cache 可以使用Redis.use() 直接来获取。示例:
        //Cache userCache= Redis.use();
        userCache.set("userid_1","admin");
        System.out.print("index.jsp:   cache set 完成#############################");

        renderJsp("index.jsp");
    }
}

运行效果:

JFinal action report -------- 2015-12-08 10:37:23 ------------------------------
Controller  : controller.IndexController.(IndexController.java:1)
Method      : index
Interceptor : interceptor.ExceptionIntoLogInterceptor.(ExceptionIntoLogInterceptor.java:1)
--------------------------------------------------------------------------------
index.jsp:   cache set 完成#############################

cache取值

 @Before(AuthInterceptor.class)
    public  void  index(){

        //System.out.print(getParaToInt()+"=====================");
        //setAttr("user", User.me.findById(4));
        Cache userCache= Redis.use("userCache");
        System.out.print("# user/index:     cache get 内容:"+userCache.get("userid_1"));
        setAttr("userPage", User.me.paginate(getParaToInt(0, 1), 10));
        render("index.html");
    }

运行结果:

JFinal action report -------- 2015-12-08 10:38:20 ------------------------------
Controller  : controller.UserController.(UserController.java:1)
Method      : index
Interceptor : interceptor.ExceptionIntoLogInterceptor.(ExceptionIntoLogInterceptor.java:1)
              interceptor.AuthInterceptor.(AuthInterceptor.java:1)
--------------------------------------------------------------------------------
# user/index:     cache get 内容:admin

注:通常情况下只会创建一个 RedisPlugin 连接一个 redis 服务端,使用 Redis.use().set(key,value)即可。

    原文作者:renner
    原文地址: https://segmentfault.com/a/1190000004113187
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞