NutzBook - 集成Ehcache及DaoCache

NutzBook - 集成Ehcache及DaoCache

Tags: Nutz

摘要

NutzBook - 集成Ehcache及DaoCache

添加相关的jar

        <!-- http://mvnrepository.com/artifact/org.nutz/nutz-plugins-daocache -->
        <dependency>
            <groupId>org.nutz</groupId>
            <artifactId>nutz-plugins-daocache</artifactId>
            <version>1.b.53.r2</version>
        </dependency>

        <!-- http://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.0</version>
        </dependency>

添加ehcache.xml

位置resources/ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="false"
    monitoring="autodetect" dynamicConfig="true" name="nutzbook">
    <!-- <diskStore path="java.io.tmpdir/shiro-ehcache"/> -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            />
    <cache name="shiro-activeSessionCache"
           maxElementsInMemory="10000"
           overflowToDisk="true"
           eternal="true"
           timeToLiveSeconds="0"
           timeToIdleSeconds="0"
           diskPersistent="true"
           diskExpiryThreadIntervalSeconds="600"/>
</ehcache>

关键点就是name=”nutzbook”,因为我们需要让shiro和nutz共享一个ehcache实例.

配置shiro.ini

打开resources下的shiro.ini,在[main]节点的末尾,加入

cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager.cacheManagerConfigFile=classpath:ehcache.xml
nutzdao_realm.cacheManager = $cacheManager

留意一下配置文件的路径,指向的就是上一小节定义的ehcache,并且让nutzdao_realm引用这个缓存管理器.

添加ehcache.js

在resources/ioc目录下添加ehcache.js, 作用是将Ehcache声明为一个bean,这样其他模块/Service就能使用它了

var ioc = {
        cacheManager : {
            type : "net.sf.ehcache.CacheManager",
            factory : "net.sf.ehcache.CacheManager#getCacheManager",
            args : ["nutzbook"] // 对应shiro.ini中指定的ehcache.xml中定义的name
        }
        /*      
        // 如果不需要shiro初始化的Ehcache, 使用下面的方式配置
        cacheManager : {
            type : "net.sf.ehcache.CacheManager",
            factory : "net.sf.ehcache.CacheManager#create"
        }
         */
};

MainSetup关联

为了排错的需要,在MainSetup中获取net.sf.ehcache.CacheManager

        CacheManager cacheManager = ioc.get(CacheManager.class);
        log.debug("Ehcache CacheManager = " + cacheManager);

修改一下BaseModule,让它也能访问CacheManager

@Inject protected CacheManager cacheManager;

改造dao.js

var ioc = {
    conf: {
        type: "org.nutz.ioc.impl.PropertiesProxy",
        fields: {
            paths: ["custom/"]
        }
    },
    dataSource: {
        type: "com.alibaba.druid.pool.DruidDataSource",
        events: {
            create: "init",
            depose: 'close'
        },
        fields: {
            url: {java: "$conf.get('db.url')"},
            username: {java: "$conf.get('db.username')"},
            password: {java: "$conf.get('db.password')"},
            testWhileIdle: true,
            validationQuery: {java: "$conf.get('db.validationQuery')"},
            maxActive: {java: "$conf.get('db.maxActive')"},
            filters: "mergeStat",
            connectionProperties: "druid.stat.slowSqlMillis=2000"
        }
    },
    dao: {
        type: "org.nutz.dao.impl.NutDaoExt", // 1.b.53或以上版本使用原版NutDao.
        args: [{refer: "dataSource"}],
        fields: {
            executor: {refer: "cacheExecutor"}
        }
    },
    cacheExecutor: {
        type: "org.nutz.plugins.cache.dao.CachedNutDaoExecutor",
        fields: {
            cacheProvider: {refer: "cacheProvider"},
            // 需要缓存的表名
            cachedTableNames: ["t_user_profile",
                //"t_user", "t_role", "t_permission", "t_role_permission"
            ]
        }
    },
    // 基于Ehcache的DaoCacheProvider
    cacheProvider: {
        type: "org.nutz.plugins.cache.dao.impl.provider.EhcacheDaoCacheProvider",
        fields: {
            cacheManager: {refer: "cacheManager"} // 引用ehcache.js中定义的CacheManager
        },
        events: {
            create: "init"
        }
    }

};

启动tomcat观察日志

访问 http://127.0.0.1:8080/ 并登陆admin
再访问 http://127.0.0.1:8080/user/profile
能看到sql相关的日志,但是如果再刷信一次,就完全没有sql相关的日志了。

2016-05-17 13:39:07,723 org.nutz.mvc.impl.UrlMappingImpl.get(UrlMappingImpl.java:92) DEBUG - Found mapping for [GET] path=/user/profile : UserProfileModule.index(UserProfileModule.java:135)
2016-05-17 13:39:07,724 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:151) DEBUG - Get 'userProfileModule'<class net.javablog.module.UserProfileModule>
2016-05-17 13:39:07,725 org.nutz.plugins.cache.dao.CachedNutDaoExecutor.exec(CachedNutDaoExecutor.java:124) DEBUG - sql = SELECT uid,nickname,email,email_checked,gender,dt,loc,ct,ut FROM t_user_profile  WHERE uid=?, tables = [t_user_profile]
2016-05-17 13:39:07,725 org.nutz.plugins.cache.dao.CachedNutDaoExecutor.exec(CachedNutDaoExecutor.java:135) DEBUG - KEY=547866925:_:_:SELECT uid,nickname,email,email_checked,gender,dt,loc,ct,ut FROM t_user_profile  WHERE uid=?:1 SQL=SELECT uid,nickname,email,email_checked,gender,dt,loc,ct,ut FROM t_user_profile  WHERE uid=?
2016-05-17 13:39:07,725 org.nutz.plugins.cache.dao.CachedNutDaoExecutor.exec(CachedNutDaoExecutor.java:141) DEBUG - cache found key=547866925:_:_:SELECT uid,nickname,email,email_checked,gender,dt,loc,ct,ut FROM t_user_profile  WHERE uid=?:1
2016-05-17 13:39:07,729 net.javablog.mvc.LogTimeProcessor.process(LogTimeProcessor.java:27) DEBUG - [ GET]URI=/user/profile 5ms
2016-05-17 13:39:07,974 org.nutz.mvc.impl.UrlMappingImpl.get(UrlMappingImpl.java:92) DEBUG - Found mapping for [GET] path=/user/profile/avatar : UserProfileModule.readAvatar(UserProfileModule.java:123)
2016-05-17 13:39:07,974 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:151) DEBUG - Get 'userProfileModule'<class net.javablog.module.UserProfileModule>
2016-05-17 13:39:07,975 org.nutz.plugins.cache.dao.CachedNutDaoExecutor.exec(CachedNutDaoExecutor.java:124) DEBUG - sql = SELECT avatar FROM t_user_profile  WHERE uid=?, tables = [t_user_profile]
2016-05-17 13:39:07,975 org.nutz.plugins.cache.dao.CachedNutDaoExecutor.exec(CachedNutDaoExecutor.java:135) DEBUG - KEY=-214898761:_:_:SELECT avatar FROM t_user_profile  WHERE uid=?:1 SQL=SELECT avatar FROM t_user_profile  WHERE uid=?
2016-05-17 13:39:07,976 org.nutz.plugins.cache.dao.CachedNutDaoExecutor.exec(CachedNutDaoExecutor.java:141) DEBUG - cache found key=-214898761:_:_:SELECT avatar FROM t_user_profile  WHERE uid=?:1
2016-05-17 13:39:07,976 org.nutz.mvc.view.RawView.render(RawView.java:115) DEBUG - File downloading ... M:\coding_test_proj\nutzbook-reading\src\main\webapp\rs\user_avatar\none.jpg
2016-05-17 13:39:07,977 net.javablog.mvc.LogTimeProcessor.process(LogTimeProcessor.java:27) DEBUG - [ GET]URI=/user/profile/avatar 3ms