├── .gitignore ├── 3.x Plan.md ├── CHANGES.md ├── LICENSE ├── README.md ├── README_EN.md ├── core ├── pom.xml ├── resources │ ├── caffeine.properties │ ├── ehcache.xml │ ├── ehcache3.xml │ ├── j2cache.properties │ └── network.xml ├── src │ └── net │ │ └── oschina │ │ └── j2cache │ │ ├── Cache.java │ │ ├── CacheChannel.java │ │ ├── CacheException.java │ │ ├── CacheExpiredListener.java │ │ ├── CacheObject.java │ │ ├── CacheProvider.java │ │ ├── CacheProviderHolder.java │ │ ├── Command.java │ │ ├── J2Cache.java │ │ ├── J2CacheBuilder.java │ │ ├── J2CacheCmd.java │ │ ├── J2CacheConfig.java │ │ ├── Level1Cache.java │ │ ├── Level2Cache.java │ │ ├── NullCache.java │ │ ├── NullCacheProvider.java │ │ ├── NullObject.java │ │ ├── caffeine │ │ ├── CaffeineCache.java │ │ └── CaffeineProvider.java │ │ ├── cluster │ │ ├── ClusterPolicy.java │ │ ├── ClusterPolicyFactory.java │ │ ├── JGroupsClusterPolicy.java │ │ ├── NoneClusterPolicy.java │ │ ├── RabbitMQClusterPolicy.java │ │ └── RocketMQClusterPolicy.java │ │ ├── ehcache │ │ ├── EhCache.java │ │ ├── EhCache3.java │ │ ├── EhCacheProvider.java │ │ └── EhCacheProvider3.java │ │ ├── lettuce │ │ ├── LettuceByteCodec.java │ │ ├── LettuceCache.java │ │ ├── LettuceCacheProvider.java │ │ ├── LettuceGenericCache.java │ │ └── LettuceHashCache.java │ │ ├── memcached │ │ ├── MemCache.java │ │ └── XmemcachedCacheProvider.java │ │ ├── redis │ │ ├── ReadonlyRedisCacheProvider.java │ │ ├── RedisCacheProvider.java │ │ ├── RedisClient.java │ │ ├── RedisGenericCache.java │ │ ├── RedisHashCache.java │ │ ├── RedisPubSubClusterPolicy.java │ │ └── RedisUtils.java │ │ └── util │ │ ├── DeserializeException.java │ │ ├── FSTSerializer.java │ │ ├── FastjsonSerializer.java │ │ ├── FseSerializer.java │ │ ├── FstJSONSerializer.java │ │ ├── FstSnappySerializer.java │ │ ├── JavaSerializer.java │ │ ├── KryoPoolSerializer.java │ │ ├── KryoSerializer.java │ │ ├── SerializationUtils.java │ │ └── Serializer.java └── test │ └── net │ └── oschina │ └── j2cache │ ├── CacheChannelTest.java │ ├── ExpiredTester.java │ ├── JSONSerializerTest.java │ ├── MultiChannelTester.java │ ├── MultiThreadTester.java │ ├── Person.java │ ├── ReferenceTest.java │ └── School.java ├── docs ├── J2Cache.png ├── J2Cache.svg ├── UPGRADE.md └── qq.png ├── modules ├── hibernate3 │ ├── Readme.md │ ├── pom.xml │ ├── src │ │ └── net │ │ │ └── oschina │ │ │ └── j2cache │ │ │ └── hibernate3 │ │ │ ├── J2CacheProvider.java │ │ │ ├── J2CacheRegion.java │ │ │ ├── J2CacheRegionFactory.java │ │ │ └── J2HibernateCache.java │ └── test │ │ ├── config │ │ ├── User.hbm.xml │ │ ├── ehcache.xml │ │ ├── hibernate.cfg.xml │ │ ├── j2cache.properties │ │ ├── log4j.properties │ │ ├── network.xml │ │ └── user.sql │ │ └── src │ │ └── net │ │ └── oschina │ │ └── j2cache │ │ └── hibernate3 │ │ ├── J2CacheProviderTester.java │ │ ├── J2CacheRegionFactoryTest.java │ │ └── User.java ├── hibernate4 │ ├── Readme.md │ ├── pom.xml │ ├── src │ │ └── net │ │ │ └── oschina │ │ │ └── j2cache │ │ │ └── hibernate4 │ │ │ ├── AbstractJ2CacheRegionFactory.java │ │ │ ├── CacheRegion.java │ │ │ ├── J2CacheCacheRegion.java │ │ │ ├── J2CacheRegionFactory.java │ │ │ ├── log │ │ │ ├── J2CacheMessageLogger.java │ │ │ └── J2CacheMessageLogger_$logger.java │ │ │ ├── nonstop │ │ │ ├── HibernateNonstopCacheExceptionHandler.java │ │ │ ├── NonStopCacheException.java │ │ │ ├── NonstopAwareCollectionRegionAccessStrategy.java │ │ │ ├── NonstopAwareEntityRegionAccessStrategy.java │ │ │ └── NonstopAwareNaturalIdRegionAccessStrategy.java │ │ │ ├── regions │ │ │ ├── J2CacheCollectionRegion.java │ │ │ ├── J2CacheDataRegion.java │ │ │ ├── J2CacheEntityRegion.java │ │ │ ├── J2CacheGeneralDataRegion.java │ │ │ ├── J2CacheNaturalIdRegion.java │ │ │ ├── J2CacheQueryResultsRegion.java │ │ │ ├── J2CacheTimestampsRegion.java │ │ │ └── J2CacheTransactionalDataRegion.java │ │ │ ├── strategy │ │ │ ├── AbstractJ2CacheAccessStrategy.java │ │ │ ├── AbstractReadWriteJ2CacheAccessStrategy.java │ │ │ ├── J2CacheAccessStrategyFactory.java │ │ │ ├── J2CacheAccessStrategyFactoryImpl.java │ │ │ ├── NonStrictReadWriteJ2CacheCollectionRegionAccessStrategy.java │ │ │ ├── NonStrictReadWriteJ2CacheEntityRegionAccessStrategy.java │ │ │ ├── NonStrictReadWriteJ2CacheNaturalIdRegionAccessStrategy.java │ │ │ ├── NonstopAccessStrategyFactory.java │ │ │ ├── ReadOnlyJ2CacheCollectionRegionAccessStrategy.java │ │ │ ├── ReadOnlyJ2CacheEntityRegionAccessStrategy.java │ │ │ ├── ReadOnlyJ2CacheNaturalIdRegionAccessStrategy.java │ │ │ ├── ReadWriteJ2CacheCollectionRegionAccessStrategy.java │ │ │ ├── ReadWriteJ2CacheEntityRegionAccessStrategy.java │ │ │ ├── ReadWriteJ2CacheNaturalIdRegionAccessStrategy.java │ │ │ ├── TransactionalJ2CacheCollectionRegionAccessStrategy.java │ │ │ ├── TransactionalJ2CacheEntityRegionAccessStrategy.java │ │ │ └── TransactionalJ2CacheNaturalIdRegionAccessStrategy.java │ │ │ └── util │ │ │ ├── SlewClock.java │ │ │ ├── TimeProviderLoader.java │ │ │ ├── Timestamper.java │ │ │ └── VicariousThreadLocal.java │ └── test │ │ ├── config │ │ ├── commons-logging.properties │ │ ├── ehcache.xml │ │ ├── j2cache.properties │ │ ├── log4j.xml │ │ ├── network.xml │ │ ├── props │ │ │ └── jdbc.properties │ │ ├── redis.properties │ │ └── spring │ │ │ ├── applicationContext-datasource.xml │ │ │ ├── applicationContext-hibernate.xml │ │ │ ├── applicationContext-transaction.xml │ │ │ └── applicationContext.xml │ │ └── src │ │ └── net │ │ └── oschina │ │ └── j2cache │ │ └── hibernate4 │ │ ├── J2CacheRegionFactoryTest.java │ │ ├── bean │ │ └── Article.java │ │ └── service │ │ └── ArticleService.java ├── hibernate5 │ ├── pom.xml │ ├── readme.md │ ├── src │ │ └── net │ │ │ └── oschina │ │ │ └── j2cache │ │ │ └── hibernate5 │ │ │ ├── AbstractJ2CacheRegionFactory.java │ │ │ ├── CacheRegion.java │ │ │ ├── J2CacheCacheRegion.java │ │ │ ├── J2CacheRegionFactory.java │ │ │ ├── log │ │ │ ├── J2CacheMessageLogger.java │ │ │ └── J2CacheMessageLogger_$logger.java │ │ │ ├── nonstop │ │ │ ├── HibernateNonstopCacheExceptionHandler.java │ │ │ ├── NonStopCacheException.java │ │ │ ├── NonstopAwareCollectionRegionAccessStrategy.java │ │ │ ├── NonstopAwareEntityRegionAccessStrategy.java │ │ │ └── NonstopAwareNaturalIdRegionAccessStrategy.java │ │ │ ├── regions │ │ │ ├── J2CacheCollectionRegion.java │ │ │ ├── J2CacheDataRegion.java │ │ │ ├── J2CacheEntityRegion.java │ │ │ ├── J2CacheGeneralDataRegion.java │ │ │ ├── J2CacheNaturalIdRegion.java │ │ │ ├── J2CacheQueryResultsRegion.java │ │ │ ├── J2CacheTimestampsRegion.java │ │ │ └── J2CacheTransactionalDataRegion.java │ │ │ ├── strategy │ │ │ ├── AbstractJ2CacheAccessStrategy.java │ │ │ ├── AbstractReadWriteJ2CacheAccessStrategy.java │ │ │ ├── J2CacheAccessStrategyFactory.java │ │ │ ├── J2CacheAccessStrategyFactoryImpl.java │ │ │ ├── NonStrictReadWriteJ2CacheCollectionRegionAccessStrategy.java │ │ │ ├── NonStrictReadWriteJ2CacheEntityRegionAccessStrategy.java │ │ │ ├── NonStrictReadWriteJ2CacheNaturalIdRegionAccessStrategy.java │ │ │ ├── NonstopAccessStrategyFactory.java │ │ │ ├── ReadOnlyJ2CacheCollectionRegionAccessStrategy.java │ │ │ ├── ReadOnlyJ2CacheEntityRegionAccessStrategy.java │ │ │ ├── ReadOnlyJ2CacheNaturalIdRegionAccessStrategy.java │ │ │ ├── ReadWriteJ2CacheCollectionRegionAccessStrategy.java │ │ │ ├── ReadWriteJ2CacheEntityRegionAccessStrategy.java │ │ │ ├── ReadWriteJ2CacheNaturalIdRegionAccessStrategy.java │ │ │ ├── TransactionalJ2CacheCollectionRegionAccessStrategy.java │ │ │ ├── TransactionalJ2CacheEntityRegionAccessStrategy.java │ │ │ └── TransactionalJ2CacheNaturalIdRegionAccessStrategy.java │ │ │ └── util │ │ │ ├── SlewClock.java │ │ │ ├── TimeProviderLoader.java │ │ │ ├── Timestamper.java │ │ │ └── lang │ │ │ └── VicariousThreadLocal.java │ └── test │ │ ├── config │ │ ├── commons-logging.properties │ │ ├── ehcache.xml │ │ ├── ehcache3.xml │ │ ├── j2cache.properties │ │ ├── log4j.xml │ │ ├── network.xml │ │ ├── props │ │ │ └── jdbc.properties │ │ ├── redis.properties │ │ └── spring │ │ │ └── applicationContext.xml │ │ └── src │ │ └── net │ │ └── oschina │ │ └── j2cache │ │ └── hibernate5 │ │ ├── J2CacheRegionFactoryTest.java │ │ ├── bean │ │ └── Article.java │ │ └── service │ │ ├── ArticleService.java │ │ └── IArticleService.java ├── mybatis │ ├── Readme.md │ ├── db.sql │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ ├── Blog.java │ │ ├── MybatisTester.java │ │ └── net │ │ │ └── oschina │ │ │ └── j2cache │ │ │ └── mybatis │ │ │ └── J2CacheAdapter.java │ │ └── resources │ │ ├── blog.xml │ │ └── mybatis.xml ├── session-manager │ ├── Readme.md │ ├── WEB-INF │ │ └── web.xml │ ├── pom.xml │ ├── src │ │ └── main │ │ │ └── java │ │ │ └── net │ │ │ └── oschina │ │ │ └── j2cache │ │ │ └── session │ │ │ ├── CacheExpiredListener.java │ │ │ ├── CacheFacade.java │ │ │ ├── CaffeineCache.java │ │ │ ├── Command.java │ │ │ ├── J2CacheSession.java │ │ │ ├── J2CacheSessionFilter.java │ │ │ ├── RedisCache.java │ │ │ ├── RedisClient.java │ │ │ ├── RedisUtils.java │ │ │ ├── Serializer.java │ │ │ └── SessionObject.java │ └── test.jsp ├── spring-boot-starter │ ├── pom.xml │ ├── readme.md │ ├── resources │ │ └── META-INF │ │ │ ├── spring-configuration-metadata.json │ │ │ └── spring.factories │ ├── src │ │ └── net │ │ │ └── oschina │ │ │ └── j2cache │ │ │ ├── autoconfigure │ │ │ ├── J2CacheAutoConfiguration.java │ │ │ ├── J2CacheConfig.java │ │ │ ├── J2CacheSpringCacheAutoConfiguration.java │ │ │ └── J2CacheSpringRedisAutoConfiguration.java │ │ │ └── cache │ │ │ └── support │ │ │ ├── J2CacheCache.java │ │ │ ├── J2CacheCacheManger.java │ │ │ ├── redis │ │ │ ├── ConfigureNotifyKeyspaceEventsAction.java │ │ │ ├── SpringRedisActiveMessageListener.java │ │ │ ├── SpringRedisCache.java │ │ │ ├── SpringRedisGenericCache.java │ │ │ ├── SpringRedisMessageListener.java │ │ │ ├── SpringRedisProvider.java │ │ │ └── SpringRedisPubSubPolicy.java │ │ │ └── util │ │ │ ├── J2CacheSerializer.java │ │ │ ├── SpringJ2CacheConfigUtil.java │ │ │ └── SpringUtil.java │ └── test │ │ └── src │ │ └── com │ │ └── test │ │ ├── ApplicationTests.java │ │ ├── bean │ │ └── TestBean.java │ │ ├── j2cache-test.properties │ │ └── service │ │ └── TestService.java ├── spring-boot2-starter │ ├── pom.xml │ ├── readme.md │ ├── resources │ │ └── META-INF │ │ │ ├── spring-configuration-metadata.json │ │ │ └── spring.factories │ ├── src │ │ └── net │ │ │ └── oschina │ │ │ └── j2cache │ │ │ ├── autoconfigure │ │ │ ├── J2CacheAutoConfiguration.java │ │ │ ├── J2CacheConfig.java │ │ │ ├── J2CacheSpringCacheAutoConfiguration.java │ │ │ └── J2CacheSpringRedisAutoConfiguration.java │ │ │ └── cache │ │ │ └── support │ │ │ ├── J2CacheCache.java │ │ │ ├── J2CacheCacheManger.java │ │ │ ├── redis │ │ │ ├── ConfigureNotifyKeyspaceEventsAction.java │ │ │ ├── SpringRedisActiveMessageListener.java │ │ │ ├── SpringRedisCache.java │ │ │ ├── SpringRedisGenericCache.java │ │ │ ├── SpringRedisMessageListener.java │ │ │ ├── SpringRedisProvider.java │ │ │ └── SpringRedisPubSubPolicy.java │ │ │ └── util │ │ │ ├── J2CacheSerializer.java │ │ │ ├── SpringJ2CacheConfigUtil.java │ │ │ └── SpringUtil.java │ └── test │ │ └── src │ │ └── com │ │ └── test │ │ ├── ApplicationTests.java │ │ ├── bean │ │ └── TestBean.java │ │ ├── j2cache-test.properties │ │ └── service │ │ └── TestService.java └── springcache │ ├── j2cache-springcache.md │ ├── pom.xml │ ├── src │ └── net │ │ └── oschina │ │ └── j2cache │ │ └── springcache │ │ ├── J2CacheSpringCacheAdapter.java │ │ └── J2CacheSpringCacheManageAdapter.java │ └── test │ └── src │ └── net │ └── oschina │ └── j2cache │ └── springcache │ └── TestJ2CacheSpringCacheManageAdapter.java ├── pom.xml ├── runtest.bat └── runtest.sh /.gitignore: -------------------------------------------------------------------------------- 1 | bin 2 | .DS_Store 3 | .settings 4 | dependency-reduced-pom.xml 5 | target 6 | *.iml 7 | .idea 8 | .project 9 | .classpath 10 | -------------------------------------------------------------------------------- /3.x Plan.md: -------------------------------------------------------------------------------- 1 | # J2Cache 3.x 版本规划 2 | 3 | J2Cache 本身作为 Java 的两级缓存框架的构想到 2.3.19 版本已经基本实现完毕,接下来 2.x 这个分支只做 Bug 的修复,不再进一步开发。 4 | 5 | 从 2018年5月23日 其开始计划 3.x 版本,3.x 一个整体的目标是实现对跨语言的支持。在一个混合语言开发系统中可以实现缓存数据的共享和更新通知。 6 | 7 | 3.0 版本代号 —— X3Cache 8 | 9 | 提供不同语言的实现: 10 | 11 | * J2Cache 12 | * PHP2Cache 13 | * Py2Cache 14 | * JS2Cache 15 | * Cpp2Cache 16 | * Go2Cache 17 | * ...... 18 | 19 | -------------------------------------------------------------------------------- /core/resources/caffeine.properties: -------------------------------------------------------------------------------- 1 | ######################################### 2 | # Caffeine configuration 3 | # [name] = size, xxxx[s|m|h|d] 4 | ######################################### 5 | 6 | default = 1000, 30m -------------------------------------------------------------------------------- /core/resources/ehcache3.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | java.lang.String 10 | java.io.Serializable 11 | 12 | 1800 13 | 14 | 15 | 1000 16 | 100 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /core/resources/network.xml: -------------------------------------------------------------------------------- 1 | 4 | 17 | 18 | 19 | 21 | 22 | 23 | 24 | 30 | 35 | 37 | 38 | 40 | 42 | 43 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/Cache.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | import java.util.Collection; 19 | import java.util.Map; 20 | 21 | /** 22 | * Cache Data Operation Interface 23 | * 24 | * @author Winter Lau(javayou@gmail.com) 25 | */ 26 | public interface Cache { 27 | 28 | /** 29 | * Get an item from the cache, nontransactionally 30 | * 31 | * @param key cache key 32 | * @return the cached object or null 33 | */ 34 | Object get(String key) ; 35 | 36 | /** 37 | * 批量获取缓存对象 38 | * @param keys cache keys 39 | * @return return key-value objects 40 | */ 41 | Map get(Collection keys); 42 | 43 | /** 44 | * 判断缓存是否存在 45 | * @param key cache key 46 | * @return true if key exists 47 | */ 48 | default boolean exists(String key) { 49 | return get(key) != null; 50 | } 51 | 52 | /** 53 | * Add an item to the cache, nontransactionally, with 54 | * failfast semantics 55 | * 56 | * @param key cache key 57 | * @param value cache value 58 | */ 59 | void put(String key, Object value); 60 | 61 | /** 62 | * 批量插入数据 63 | * @param elements objects to be put in cache 64 | */ 65 | void put(Map elements); 66 | 67 | /** 68 | * Return all keys 69 | * 70 | * @return 返回键的集合 71 | */ 72 | Collection keys() ; 73 | 74 | /** 75 | * Remove items from the cache 76 | * 77 | * @param keys Cache key 78 | */ 79 | void evict(String...keys); 80 | 81 | /** 82 | * Clear the cache 83 | */ 84 | void clear(); 85 | 86 | } 87 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/CacheException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | /** 19 | * J2Cache exception 20 | * 21 | * @author Winter Lau (javayou@gmail.com) 22 | */ 23 | public class CacheException extends RuntimeException { 24 | 25 | public CacheException(String s) { 26 | super(s); 27 | } 28 | 29 | public CacheException(String s, Throwable e) { 30 | super(s, e); 31 | } 32 | 33 | public CacheException(Throwable e) { 34 | super(e); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/CacheExpiredListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | /** 19 | * When cached data expired in ehcache, this listener will be invoked. 20 | * 21 | * @author Winter Lau(javayou@gmail.com) 22 | */ 23 | public interface CacheExpiredListener { 24 | 25 | /** 26 | * 缓存因为超时失效后触发的通知 27 | * @param region 缓存 region 28 | * @param key 缓存 key 29 | */ 30 | void notifyElementExpired(String region, String key) ; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/CacheProvider.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | import java.util.Collection; 19 | import java.util.Properties; 20 | 21 | /** 22 | * Support for pluggable caches. 23 | * @author Winter Lau(javayou@gmail.com) 24 | */ 25 | public interface CacheProvider { 26 | 27 | /** 28 | * 缓存的标识名称 29 | * @return return cache provider name 30 | */ 31 | String name(); 32 | 33 | /** 34 | * 缓存的层级 35 | * @return current provider level 36 | */ 37 | int level(); 38 | 39 | default boolean isLevel(int level) { 40 | return (level() & level) == level; 41 | } 42 | 43 | /** 44 | * Configure the cache 45 | * 46 | * @param regionName the name of the cache region 47 | * @param listener listener for expired elements 48 | * @return return cache instance 49 | */ 50 | Cache buildCache(String regionName, CacheExpiredListener listener); 51 | 52 | /** 53 | * Configure the cache with timeToLiveInMills 54 | * @param region cache region name 55 | * @param timeToLiveInSeconds time to live in second 56 | * @param listener listener for expired elements 57 | * @return return cache instance 58 | */ 59 | Cache buildCache(String region, long timeToLiveInSeconds, CacheExpiredListener listener); 60 | 61 | /** 62 | * Remove a cache region 63 | * @param region cache region name 64 | */ 65 | default void removeCache(String region) {} 66 | 67 | /** 68 | * Return all channels defined in first level cache 69 | * @return all regions name 70 | */ 71 | Collection regions(); 72 | 73 | /** 74 | * Callback to perform any necessary initialization of the underlying cache implementation 75 | * during SessionFactory construction. 76 | * 77 | * @param props current configuration settings. 78 | */ 79 | void start(Properties props); 80 | 81 | /** 82 | * Callback to perform any necessary cleanup of the underlying cache implementation 83 | * during SessionFactory.close(). 84 | */ 85 | void stop(); 86 | 87 | } 88 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/J2Cache.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | import java.io.IOException; 19 | 20 | /** 21 | * J2Cache 的缓存入口 22 | * @author Winter Lau(javayou@gmail.com) 23 | */ 24 | public class J2Cache { 25 | 26 | private final static String CONFIG_FILE = "/j2cache.properties"; 27 | 28 | private final static J2CacheBuilder builder; 29 | 30 | static { 31 | try { 32 | J2CacheConfig config = J2CacheConfig.initFromConfig(CONFIG_FILE); 33 | builder = J2CacheBuilder.init(config); 34 | } catch (IOException e) { 35 | throw new CacheException("Failed to load j2cache configuration " + CONFIG_FILE, e); 36 | } 37 | } 38 | 39 | /** 40 | * 返回缓存操作接口 41 | * @return CacheChannel 42 | */ 43 | public static CacheChannel getChannel(){ 44 | return builder.getChannel(); 45 | } 46 | 47 | /** 48 | * 关闭 J2Cache 49 | */ 50 | public static void close() { 51 | builder.close(); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/Level1Cache.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | /** 19 | * 一级缓存接口 20 | * @author Winter Lau(javayou@gmail.com) 21 | */ 22 | public interface Level1Cache extends Cache { 23 | 24 | /** 25 | * 返回该缓存区域的 TTL 设置(单位:秒) 26 | * @return true if cache support ttl setting 27 | */ 28 | long ttl(); 29 | 30 | /** 31 | * 返回该缓存区域中,内存存储对象的最大数量 32 | * @return cache size in memory 33 | */ 34 | long size(); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/NullCache.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | import java.util.Collection; 19 | import java.util.Collections; 20 | import java.util.List; 21 | import java.util.Map; 22 | 23 | /** 24 | * 空的缓存Provider 25 | * @author Winter Lau(javayou@gmail.com) 26 | */ 27 | public class NullCache implements Level1Cache, Level2Cache { 28 | 29 | @Override 30 | public long ttl() { 31 | return -1; 32 | } 33 | 34 | @Override 35 | public long size() { 36 | return 0; 37 | } 38 | 39 | @Override 40 | public Object get(String key) { 41 | return null; 42 | } 43 | 44 | @Override 45 | public void put(String key, Object value) { 46 | } 47 | 48 | @Override 49 | public Collection keys() { 50 | return Collections.emptyList(); 51 | } 52 | 53 | @Override 54 | public Map get(Collection keys) { 55 | return Collections.emptyMap(); 56 | } 57 | 58 | @Override 59 | public boolean exists(String key) { 60 | return false; 61 | } 62 | 63 | @Override 64 | public void put(Map elements) { 65 | } 66 | 67 | @Override 68 | public byte[] getBytes(String key) { 69 | return null; 70 | } 71 | 72 | @Override 73 | public List getBytes(Collection key) { 74 | return Collections.emptyList(); 75 | } 76 | 77 | @Override 78 | public void setBytes(String key, byte[] bytes) { 79 | } 80 | 81 | @Override 82 | public void setBytes(Map bytes) { 83 | } 84 | 85 | @Override 86 | public void evict(String...keys) { 87 | } 88 | 89 | @Override 90 | public void clear() { 91 | 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/NullCacheProvider.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | import java.util.Collection; 19 | import java.util.Properties; 20 | 21 | /** 22 | * @author Winter Lau(javayou@gmail.com) 23 | */ 24 | public class NullCacheProvider implements CacheProvider { 25 | 26 | private final static NullCache cache = new NullCache(); 27 | 28 | @Override 29 | public String name() { 30 | return "none"; 31 | } 32 | 33 | @Override 34 | public int level() { 35 | return CacheObject.LEVEL_1 | CacheObject.LEVEL_2; 36 | } 37 | 38 | @Override 39 | public Cache buildCache(String regionName, CacheExpiredListener listener) throws CacheException { 40 | return cache; 41 | } 42 | 43 | @Override 44 | public Cache buildCache(String region, long timeToLiveInSeconds, CacheExpiredListener listener) { 45 | return cache; 46 | } 47 | 48 | @Override 49 | public void start(Properties props) throws CacheException { 50 | } 51 | 52 | @Override 53 | public Collection regions() { 54 | return null; 55 | } 56 | 57 | @Override 58 | public void stop() { 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/NullObject.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | import java.io.Serializable; 19 | 20 | /** 21 | * Null Object 22 | * @author Winter Lau(javayou@gmail.com) 23 | */ 24 | public class NullObject implements Serializable { 25 | } 26 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/caffeine/CaffeineCache.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.caffeine; 17 | 18 | import com.github.benmanes.caffeine.cache.Cache; 19 | import net.oschina.j2cache.Level1Cache; 20 | 21 | import java.util.Arrays; 22 | import java.util.Collection; 23 | import java.util.Map; 24 | 25 | /** 26 | * Caffeine cache 27 | * 28 | * @author Winter Lau(javayou@gmail.com) 29 | */ 30 | public class CaffeineCache implements Level1Cache { 31 | 32 | private Cache cache; 33 | private long size ; 34 | private long expire ; 35 | 36 | public CaffeineCache(Cache cache, long size, long expire) { 37 | this.cache = cache; 38 | this.size = size; 39 | this.expire = expire; 40 | } 41 | 42 | @Override 43 | public long ttl() { 44 | return expire; 45 | } 46 | 47 | @Override 48 | public long size() { return size; } 49 | 50 | @Override 51 | public Object get(String key) { 52 | return cache.getIfPresent(key); 53 | } 54 | 55 | @Override 56 | public Map get(Collection keys) { 57 | return cache.getAllPresent(keys); 58 | } 59 | 60 | @Override 61 | public void put(String key, Object value) { 62 | cache.put(key, value); 63 | } 64 | 65 | @Override 66 | public void put(Map elements) { 67 | cache.putAll(elements); 68 | } 69 | 70 | @Override 71 | public Collection keys() { 72 | return cache.asMap().keySet(); 73 | } 74 | 75 | @Override 76 | public void evict(String...keys) { 77 | cache.invalidateAll(Arrays.asList(keys)); 78 | } 79 | 80 | @Override 81 | public void clear() { 82 | cache.invalidateAll(); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/cluster/NoneClusterPolicy.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.cluster; 17 | 18 | import net.oschina.j2cache.CacheProviderHolder; 19 | import net.oschina.j2cache.Command; 20 | 21 | import java.util.Properties; 22 | 23 | /** 24 | * 实现空的集群通知策略 25 | * @author Winter Lau(javayou@gmail.com) 26 | */ 27 | public class NoneClusterPolicy implements ClusterPolicy { 28 | 29 | private int LOCAL_COMMAND_ID = Command.genRandomSrc(); //命令源标识,随机生成,每个节点都有唯一标识 30 | 31 | @Override 32 | public boolean isLocalCommand(Command cmd) { 33 | return cmd.getSrc() == LOCAL_COMMAND_ID; 34 | } 35 | 36 | @Override 37 | public void connect(Properties props, CacheProviderHolder holder) { 38 | } 39 | 40 | @Override 41 | public void disconnect() { 42 | } 43 | 44 | @Override 45 | public void publish(Command cmd) { 46 | } 47 | 48 | @Override 49 | public void evict(String region, String... keys) { 50 | } 51 | 52 | @Override 53 | public void clear(String region) { 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/lettuce/LettuceByteCodec.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.lettuce; 17 | 18 | import io.lettuce.core.codec.RedisCodec; 19 | 20 | import java.nio.ByteBuffer; 21 | 22 | /** 23 | * 使用字节编码 24 | * @author Winter Lau (javayou@gmail.com) 25 | */ 26 | public class LettuceByteCodec implements RedisCodec { 27 | 28 | private static final byte[] EMPTY = new byte[0]; 29 | 30 | @Override 31 | public String decodeKey(ByteBuffer byteBuffer) { 32 | return new String(getBytes(byteBuffer)); 33 | } 34 | 35 | @Override 36 | public byte[] decodeValue(ByteBuffer byteBuffer) { 37 | return getBytes(byteBuffer); 38 | } 39 | 40 | @Override 41 | public ByteBuffer encodeKey(String s) { 42 | return ByteBuffer.wrap(s.getBytes()); 43 | } 44 | 45 | @Override 46 | public ByteBuffer encodeValue(byte[] bytes) { 47 | return ByteBuffer.wrap(bytes); 48 | } 49 | 50 | 51 | private static byte[] getBytes(ByteBuffer buffer) { 52 | int remaining = buffer.remaining(); 53 | 54 | if (remaining == 0) { 55 | return EMPTY; 56 | } 57 | 58 | byte[] b = new byte[remaining]; 59 | buffer.get(b); 60 | return b; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/lettuce/LettuceCache.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.lettuce; 17 | 18 | import io.lettuce.core.api.StatefulConnection; 19 | import io.lettuce.core.api.StatefulRedisConnection; 20 | import io.lettuce.core.api.sync.BaseRedisCommands; 21 | import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; 22 | import net.oschina.j2cache.CacheException; 23 | import net.oschina.j2cache.Level2Cache; 24 | import org.apache.commons.pool2.impl.GenericObjectPool; 25 | 26 | /** 27 | * Lettuce 的基类,封装了普通 Redis 连接和集群 Redis 连接的差异 28 | * 29 | * @author Winter Lau(javayou@gmail.com) 30 | */ 31 | public abstract class LettuceCache implements Level2Cache { 32 | 33 | protected String namespace; 34 | protected String region; 35 | protected GenericObjectPool> pool; 36 | protected int scanCount; 37 | 38 | protected StatefulConnection connect() { 39 | try { 40 | return pool.borrowObject(); 41 | } catch (Exception e) { 42 | throw new CacheException(e); 43 | } 44 | } 45 | 46 | protected BaseRedisCommands sync(StatefulConnection conn) { 47 | if(conn instanceof StatefulRedisClusterConnection) 48 | return ((StatefulRedisClusterConnection)conn).sync(); 49 | else if(conn instanceof StatefulRedisConnection) 50 | return ((StatefulRedisConnection)conn).sync(); 51 | return null; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/redis/RedisUtils.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.redis; 2 | 3 | import redis.clients.jedis.JedisPoolConfig; 4 | 5 | import java.util.Properties; 6 | 7 | public class RedisUtils { 8 | 9 | /** 10 | * 初始化 Redis 连接池 11 | * @param props j2cache.properties 12 | * @param prefix configuration prefix 13 | * @return redis connection pool configuration object 14 | */ 15 | public final static JedisPoolConfig newPoolConfig(Properties props, String prefix) { 16 | JedisPoolConfig cfg = new JedisPoolConfig(); 17 | cfg.setMaxTotal(Integer.valueOf(props.getProperty(key(prefix,"maxTotal"), "-1"))); 18 | cfg.setMaxIdle(Integer.valueOf(props.getProperty(key(prefix,"maxIdle"), "100"))); 19 | cfg.setMaxWaitMillis(Integer.valueOf(props.getProperty(key(prefix,"maxWaitMillis"), "100"))); 20 | cfg.setMinEvictableIdleTimeMillis(Integer.valueOf(props.getProperty(key(prefix,"minEvictableIdleTimeMillis"), "864000000"))); 21 | cfg.setMinIdle(Integer.valueOf(props.getProperty(key(prefix,"minIdle"), "10"))); 22 | cfg.setNumTestsPerEvictionRun(Integer.valueOf(props.getProperty(key(prefix,"numTestsPerEvictionRun"), "10"))); 23 | cfg.setLifo(Boolean.valueOf(props.getProperty(key(prefix,"lifo"), "false"))); 24 | cfg.setSoftMinEvictableIdleTimeMillis(Integer.valueOf((String)props.getOrDefault(key(prefix,"softMinEvictableIdleTimeMillis"), "10"))); 25 | cfg.setTestOnBorrow(Boolean.valueOf(props.getProperty(key(prefix,"testOnBorrow"), "true"))); 26 | cfg.setTestOnReturn(Boolean.valueOf(props.getProperty(key(prefix,"testOnReturn"), "false"))); 27 | cfg.setTestWhileIdle(Boolean.valueOf(props.getProperty(key(prefix,"testWhileIdle"), "true"))); 28 | cfg.setTimeBetweenEvictionRunsMillis(Integer.valueOf(props.getProperty(key(prefix,"timeBetweenEvictionRunsMillis"), "300000"))); 29 | cfg.setBlockWhenExhausted(Boolean.valueOf(props.getProperty(key(prefix,"blockWhenExhausted"), "false"))); 30 | return cfg; 31 | } 32 | 33 | private static String key(String prefix, String key) { 34 | return (prefix == null) ? key : prefix + "." + key; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/util/DeserializeException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.util; 17 | 18 | /** 19 | * 反序列化的对象兼容异常 20 | * @author Winter Lau(javayou@gmail.com) 21 | */ 22 | public class DeserializeException extends RuntimeException { 23 | 24 | public DeserializeException(String message) { 25 | super(message); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/util/FSTSerializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.util; 17 | 18 | import org.nustaq.serialization.FSTConfiguration; 19 | 20 | /** 21 | * 使用 FST 实现序列化 22 | * 23 | * @author Winter Lau(javayou@gmail.com) 24 | */ 25 | public class FSTSerializer implements Serializer { 26 | 27 | private FSTConfiguration fstConfiguration ; 28 | 29 | public FSTSerializer() { 30 | fstConfiguration = FSTConfiguration.getDefaultConfiguration(); 31 | fstConfiguration.setClassLoader(Thread.currentThread().getContextClassLoader()); 32 | } 33 | 34 | @Override 35 | public String name() { 36 | return "fst"; 37 | } 38 | 39 | @Override 40 | public byte[] serialize(Object obj) { 41 | return fstConfiguration.asByteArray(obj); 42 | } 43 | 44 | @Override 45 | public Object deserialize(byte[] bytes) { 46 | return fstConfiguration.asObject(bytes); 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/util/FastjsonSerializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.util; 17 | 18 | import com.alibaba.fastjson.JSON; 19 | import com.alibaba.fastjson.parser.Feature; 20 | import com.alibaba.fastjson.serializer.SerializerFeature; 21 | 22 | /** 23 | * 使用 fastjson 进行对象的 JSON 格式序列化 24 | * 25 | * @author Winter Lau(javayou@gmail.com) 26 | */ 27 | public class FastjsonSerializer implements Serializer { 28 | 29 | @Override 30 | public String name() { 31 | return "fastjson"; 32 | } 33 | 34 | @Override 35 | public byte[] serialize(Object obj) { 36 | return JSON.toJSONString(obj, SerializerFeature.WriteClassName).getBytes(); 37 | } 38 | 39 | @Override 40 | public Object deserialize(byte[] bytes) { 41 | return JSON.parse(new String(bytes), Feature.SupportAutoType); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/util/FseSerializer.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015-2020, whcrow (v@whcrow.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.util; 17 | 18 | import com.jfirer.fse.ByteArray; 19 | import com.jfirer.fse.Fse; 20 | 21 | /** 22 | * 使用 fse 实现序列化 23 | * 24 | * @author whcrow (v@whcrow.com) 25 | */ 26 | public class FseSerializer implements Serializer { 27 | 28 | @Override 29 | public String name() { 30 | return "fse"; 31 | } 32 | 33 | @Override 34 | public byte[] serialize(Object obj) { 35 | ByteArray buf = ByteArray.allocate(100); 36 | new Fse().serialize(obj, buf); 37 | byte[] resultBytes = buf.toArray(); 38 | buf.clear(); 39 | return resultBytes; 40 | } 41 | 42 | @Override 43 | public Object deserialize(byte[] bytes) { 44 | if (bytes == null || bytes.length == 0) { 45 | return null; 46 | } 47 | ByteArray buf = ByteArray.allocate(100); 48 | buf.put(bytes); 49 | Object result = new Fse().deSerialize(buf); 50 | buf.clear(); 51 | return result; 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/util/FstSnappySerializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.util; 17 | 18 | import java.io.IOException; 19 | 20 | import org.xerial.snappy.Snappy; 21 | 22 | /** 23 | * 在 @FSTSerializer 的基础上增加 snappy ,也就是压缩 24 | */ 25 | public class FstSnappySerializer implements Serializer { 26 | 27 | private final Serializer inner; 28 | 29 | public FstSnappySerializer() { 30 | this(new FSTSerializer()); 31 | } 32 | 33 | public FstSnappySerializer(Serializer innerSerializer) { 34 | this.inner = innerSerializer; 35 | } 36 | 37 | 38 | @Override 39 | public String name() { 40 | return "fst-snappy"; 41 | } 42 | 43 | @Override 44 | public byte[] serialize(Object obj) throws IOException { 45 | return Snappy.compress(inner.serialize(obj)); 46 | } 47 | 48 | @Override 49 | public Object deserialize(byte[] bytes) throws IOException { 50 | if (bytes == null || bytes.length == 0) 51 | return null; 52 | return inner.deserialize(Snappy.uncompress(bytes)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/util/JavaSerializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.util; 17 | 18 | import net.oschina.j2cache.CacheException; 19 | 20 | import java.io.*; 21 | 22 | /** 23 | * 标准的 Java 序列化 24 | * 25 | * @author Winter Lau(javayou@gmail.com) 26 | */ 27 | public class JavaSerializer implements Serializer { 28 | 29 | @Override 30 | public String name() { 31 | return "java"; 32 | } 33 | 34 | @Override 35 | public byte[] serialize(Object obj) throws IOException { 36 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 37 | try (ObjectOutputStream oos = new ObjectOutputStream(baos)){ 38 | oos.writeObject(obj); 39 | return baos.toByteArray(); 40 | } 41 | } 42 | 43 | @Override 44 | public Object deserialize(byte[] bits) throws IOException { 45 | if(bits == null || bits.length == 0) 46 | return null; 47 | ByteArrayInputStream bais = new ByteArrayInputStream(bits); 48 | try (ObjectInputStream ois = new ObjectInputStream(bais)){ 49 | return ois.readObject(); 50 | } catch (ClassNotFoundException e) { 51 | throw new CacheException(e); 52 | } 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/util/KryoSerializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.util; 17 | 18 | import com.esotericsoftware.kryo.Kryo; 19 | import com.esotericsoftware.kryo.io.Input; 20 | import com.esotericsoftware.kryo.io.Output; 21 | 22 | import java.io.ByteArrayInputStream; 23 | import java.io.ByteArrayOutputStream; 24 | import java.io.IOException; 25 | 26 | /** 27 | * 使用 Kryo 实现序列化 28 | * 29 | * @author Winter Lau(javayou@gmail.com) 30 | */ 31 | public class KryoSerializer implements Serializer { 32 | 33 | @Override 34 | public String name() { 35 | return "kryo"; 36 | } 37 | 38 | @Override 39 | public byte[] serialize(Object obj) { 40 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 41 | try (Output output = new Output(baos);){ 42 | new Kryo().writeClassAndObject(output, obj); 43 | output.flush(); 44 | return baos.toByteArray(); 45 | } 46 | } 47 | 48 | @Override 49 | public Object deserialize(byte[] bits) { 50 | if(bits == null || bits.length == 0) 51 | return null; 52 | try (Input ois = new Input(new ByteArrayInputStream(bits))){ 53 | return new Kryo().readClassAndObject(ois); 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /core/src/net/oschina/j2cache/util/Serializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.util; 17 | 18 | import java.io.IOException; 19 | 20 | /** 21 | * 对象序列化接口 22 | * 23 | * @author Winter Lau(javayou@gmail.com) 24 | */ 25 | public interface Serializer { 26 | 27 | /** 28 | * 序列化器的名称,该方法仅用于打印日志的时候显示 29 | * @return 返回序列化器名称 30 | */ 31 | String name(); 32 | 33 | /** 34 | * 对象序列化到字节数组 35 | * @param obj 待序列化的对象 36 | * @return 返回序列化数据 37 | * @throws IOException io exception 38 | */ 39 | byte[] serialize(Object obj) throws IOException ; 40 | 41 | /** 42 | * 反序列化到对象 43 | * @param bytes 反序列化的数据 44 | * @return 返回序列化对象 45 | * @throws IOException io exception 46 | */ 47 | Object deserialize(byte[] bytes) throws IOException ; 48 | 49 | } 50 | -------------------------------------------------------------------------------- /core/test/net/oschina/j2cache/ExpiredTester.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache; 17 | 18 | /** 19 | * 用来测试缓存的有效期 20 | */ 21 | public class ExpiredTester { 22 | 23 | public static void main(String[] args) throws InterruptedException { 24 | 25 | CacheChannel cache = J2Cache.getChannel(); 26 | 27 | cache.set("default", "name", "Winter Lau"); 28 | 29 | for(int i=1;i<=20;i++) { 30 | 31 | System.out.printf("%d: %s\n", i, cache.get("default", "name")); 32 | 33 | Thread.sleep(1000); 34 | } 35 | 36 | cache.close(); 37 | 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /core/test/net/oschina/j2cache/JSONSerializerTest.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache; 2 | 3 | import net.oschina.j2cache.util.FastjsonSerializer; 4 | import net.oschina.j2cache.util.FstJSONSerializer; 5 | import org.junit.After; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | 9 | import java.util.Arrays; 10 | import java.util.HashMap; 11 | import java.util.Properties; 12 | 13 | 14 | import static org.junit.Assert.*; 15 | 16 | /** 17 | * 测试 json 序列化 18 | */ 19 | public class JSONSerializerTest { 20 | 21 | Properties mapping; 22 | Person person ; 23 | 24 | @Before 25 | public void setUp() { 26 | person = new Person(); 27 | person.setName("Winter Lau"); 28 | person.setAge(19); 29 | person.setSchoolList(Arrays.asList(new School("西北工业大学"), new School("泉州第五中学"), new School("城东中学"), new School("洛南小学"))); 30 | person.setJobs(new HashMap(){{ 31 | put("creawor", 3); 32 | put("moabc", 5); 33 | put("huateng", 3); 34 | put("oschina", 8); 35 | }}); 36 | 37 | mapping = new Properties(); 38 | mapping.setProperty("map.person", "net.oschina.j2cache.Person"); 39 | mapping.setProperty("map.school", "net.oschina.j2cache.School"); 40 | mapping.setProperty("map.list", "java.util.Arrays$ArrayList"); 41 | } 42 | 43 | @After 44 | public void tearDown() { 45 | person = null; 46 | mapping = null; 47 | } 48 | 49 | @Test 50 | public void fst_json() { 51 | 52 | FstJSONSerializer serializer = new FstJSONSerializer(mapping); 53 | 54 | byte[] bytes = serializer.serialize(person); 55 | 56 | System.out.println(new String(bytes)); 57 | 58 | 59 | Person p = (Person)serializer.deserialize(bytes); 60 | 61 | assertEquals(person.getName(), p.getName()); 62 | assertEquals(person.getAge(), p.getAge()); 63 | 64 | System.out.println(p); 65 | 66 | } 67 | 68 | 69 | @Test 70 | public void fast_json() { 71 | 72 | FastjsonSerializer serializer = new FastjsonSerializer(); 73 | 74 | byte[] bytes = serializer.serialize(person); 75 | 76 | System.out.println(new String(bytes)); 77 | 78 | 79 | Person p = (Person)serializer.deserialize(bytes); 80 | 81 | assertEquals(person.getName(), p.getName()); 82 | assertEquals(person.getAge(), p.getAge()); 83 | 84 | System.out.println(p); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /core/test/net/oschina/j2cache/MultiChannelTester.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache; 2 | 3 | /** 4 | * 测试一个应用里多个 CacheChannel 实例 5 | */ 6 | public class MultiChannelTester { 7 | 8 | public static void main( String[] args ) 9 | { 10 | try { 11 | 12 | J2CacheConfig config_admin = J2CacheConfig.initFromConfig("/j2cache.properties"); 13 | J2CacheConfig config_service = J2CacheConfig.initFromConfig("/j2cache2.properties"); 14 | 15 | config_admin.dump(System.out); 16 | 17 | System.out.println("---------------------------------------------"); 18 | 19 | config_service.dump(System.out); 20 | 21 | CacheChannel channel_admin = J2CacheBuilder.init(config_admin).getChannel(); 22 | CacheChannel channel_service = J2CacheBuilder.init(config_service).getChannel(); 23 | 24 | channel_admin.set("test-admin", "test-key-admin", "test-value-admin"); 25 | channel_service.set("test-service", "test-key-service", "test-value-service"); 26 | 27 | } catch (Exception e) { 28 | e.printStackTrace(); 29 | } 30 | 31 | System.exit(0); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /core/test/net/oschina/j2cache/MultiThreadTester.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.Executors; 5 | import java.util.concurrent.TimeUnit; 6 | 7 | /** 8 | * 对 J2Cache 进行多线程测试 9 | */ 10 | public class MultiThreadTester { 11 | 12 | public static void main(String[] args) throws InterruptedException { 13 | CacheChannel cache = J2Cache.getChannel(); 14 | 15 | String region = "Users"; 16 | String key = "ld"; 17 | 18 | ExecutorService threadPool = Executors.newCachedThreadPool(); 19 | 20 | cache.evict(region, key); 21 | //cache.set(region, key, "Winter Lau"); 22 | 23 | for(int i=0;i<100;i++) { 24 | final int seq = i; 25 | threadPool.execute(() -> { 26 | String name = "Thread-" + seq; 27 | for(int j=0;j<1;j++) { 28 | long ct = System.currentTimeMillis(); 29 | System.out.printf("%s -> %s (%dms)\n", name, cache.get(region, key), (System.currentTimeMillis()-ct)); 30 | } 31 | }); 32 | } 33 | 34 | threadPool.shutdown(); 35 | threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); 36 | 37 | System.exit(0); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /core/test/net/oschina/j2cache/Person.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache; 2 | 3 | import java.io.Serializable; 4 | import java.math.BigInteger; 5 | import java.util.Date; 6 | import java.util.HashMap; 7 | import java.util.List; 8 | 9 | /** 10 | * 测试 JSON 序列化的类 11 | */ 12 | public class Person implements Serializable { 13 | 14 | private String name; 15 | private int age; 16 | private BigInteger seconds = new BigInteger("100"); 17 | private List schoolList; 18 | private HashMap jobs; 19 | 20 | public Date getCreate_time() { 21 | return create_time; 22 | } 23 | 24 | public void setCreate_time(Date create_time) { 25 | this.create_time = create_time; 26 | } 27 | 28 | private Date create_time = new Date(System.currentTimeMillis()); 29 | 30 | public String getName() { 31 | return name; 32 | } 33 | 34 | public void setName(String name) { 35 | this.name = name; 36 | } 37 | 38 | public int getAge() { 39 | return age; 40 | } 41 | 42 | public void setAge(int age) { 43 | this.age = age; 44 | } 45 | 46 | public BigInteger getSeconds() { 47 | return seconds; 48 | } 49 | 50 | public void setSeconds(BigInteger seconds) { 51 | this.seconds = seconds; 52 | } 53 | 54 | public List getSchoolList() { 55 | return schoolList; 56 | } 57 | 58 | public void setSchoolList(List schoolList) { 59 | this.schoolList = schoolList; 60 | } 61 | 62 | public HashMap getJobs() { 63 | return jobs; 64 | } 65 | 66 | public void setJobs(HashMap jobs) { 67 | this.jobs = jobs; 68 | } 69 | 70 | @Override 71 | public String toString() { 72 | String str = String.format("NAME:%s,AGE:%d%n", name, age); 73 | for(School sch : schoolList) { 74 | str += "\t"; 75 | str += sch; 76 | } 77 | 78 | for(String key : jobs.keySet()) 79 | str += String.format("\tNAME:%s,YEARS:%d%n", key, jobs.get(key)); 80 | 81 | return str; 82 | } 83 | 84 | } -------------------------------------------------------------------------------- /core/test/net/oschina/j2cache/ReferenceTest.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache; 2 | 3 | import java.lang.ref.PhantomReference; 4 | import java.lang.ref.Reference; 5 | import java.lang.ref.ReferenceQueue; 6 | import java.lang.ref.WeakReference; 7 | import java.util.LinkedList; 8 | 9 | /** 10 | * Java 引用测试 11 | */ 12 | public class ReferenceTest { 13 | 14 | private static ReferenceQueue rq = new ReferenceQueue<>(); 15 | 16 | public static void checkQueue() { 17 | Reference ref = null; 18 | while ((ref = rq.poll()) != null) { 19 | System.out.println("In queue: " + ((VeryBigWeakReference) (ref)).id); 20 | } 21 | } 22 | 23 | public static void main2(String args[]) { 24 | int size = 3; 25 | LinkedList> weakList = new LinkedList<>(); 26 | for (int i = 0; i < size; i++) { 27 | weakList.add(new VeryBigWeakReference(new VeryBig("Weak " + i), rq)); 28 | System.out.println("Just created weak: " + weakList.getLast()); 29 | 30 | } 31 | 32 | System.gc(); 33 | try { // 下面休息几分钟,让上面的垃圾回收线程运行完成 34 | Thread.currentThread().sleep(6000); 35 | } catch (InterruptedException e) { 36 | e.printStackTrace(); 37 | } 38 | checkQueue(); 39 | } 40 | 41 | public static void main1(String[] args) { 42 | WeakReference sr = new WeakReference<>(new String("hello")); 43 | System.out.println(sr.get()); 44 | System.gc(); //通知JVM的gc进行垃圾回收 45 | System.out.println(sr.get()); 46 | } 47 | 48 | 49 | public static void main(String[] args) { 50 | ReferenceQueue queue = new ReferenceQueue<>(); 51 | PhantomReference pr = new PhantomReference<>(new String("hello"), queue); 52 | System.out.println(pr.get()); 53 | } 54 | } 55 | 56 | class VeryBig { 57 | public String id; 58 | // 占用空间,让线程进行回收 59 | byte[] b = new byte[2 * 1024]; 60 | 61 | public VeryBig(String id) { 62 | this.id = id; 63 | } 64 | 65 | protected void finalize() { 66 | System.out.println("Finalizing VeryBig " + id); 67 | } 68 | } 69 | 70 | class VeryBigWeakReference extends WeakReference { 71 | public String id; 72 | 73 | public VeryBigWeakReference(VeryBig big, ReferenceQueue rq) { 74 | super(big, rq); 75 | this.id = big.id; 76 | } 77 | 78 | @Override 79 | protected void finalize() { 80 | System.out.println("Finalizing VeryBigWeakReference " + id); 81 | } 82 | } -------------------------------------------------------------------------------- /core/test/net/oschina/j2cache/School.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache; 2 | 3 | import java.io.Serializable; 4 | 5 | public class School implements Serializable { 6 | 7 | private String name; 8 | private int random = (int)(Math.random() * 1000); 9 | 10 | public School(String name) { 11 | this.name = name; 12 | } 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public int getRandom() { 23 | return random; 24 | } 25 | 26 | public void setRandom(int random) { 27 | this.random = random; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return String.format("NAME:%s,RANDOM:%d%n", name, random); 33 | } 34 | } -------------------------------------------------------------------------------- /docs/J2Cache.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oschina/J2Cache/7838cabb19c44df88257561fc6f53b5d7ffbbb80/docs/J2Cache.png -------------------------------------------------------------------------------- /docs/J2Cache.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Group 2 5 | Created with Sketch. 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /docs/UPGRADE.md: -------------------------------------------------------------------------------- 1 | J2Cache 版本更新流程 2 | 3 | 1. 完成代码开发和测试 4 | 2. 修改对应模块 pom.xml 中关于版本的定义 (version) 5 | 3. 修改 README.md 中关于 maven 部分的引用版本 6 | 4. 在 CHANGES.md 中描述改进内容 7 | 5. 发布到 maven 中央库 (mvn deploy -P release -DskipTests=true) 8 | 6. 到 https://oss.sonatype.org/#stagingRepositories 发布新版 9 | 7. 推送代码到仓库 10 | 8. 打标签、创建 Release 发行版 11 | 9. 社区投递更新新闻 -------------------------------------------------------------------------------- /docs/qq.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oschina/J2Cache/7838cabb19c44df88257561fc6f53b5d7ffbbb80/docs/qq.png -------------------------------------------------------------------------------- /modules/hibernate3/Readme.md: -------------------------------------------------------------------------------- 1 | 对 Hibernate 3.x 的支持 -------------------------------------------------------------------------------- /modules/hibernate3/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | net.oschina.j2cache 5 | j2cache 6 | 2.8.0-release 7 | ../../pom.xml 8 | 9 | 10 | 4.0.0 11 | j2cache-hibernate3 12 | 13 | 14 | src 15 | test/src 16 | 17 | 18 | 19 | 20 | net.oschina.j2cache 21 | j2cache-core 22 | provided 23 | 24 | 25 | org.hibernate 26 | hibernate-core 27 | 3.3.2.GA 28 | compile 29 | 30 | 31 | 32 | J2Cache - hibernate3 33 | 34 | 35 | -------------------------------------------------------------------------------- /modules/hibernate3/src/net/oschina/j2cache/hibernate3/J2CacheProvider.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, liao. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate3; 17 | 18 | import net.oschina.j2cache.J2Cache; 19 | 20 | import org.hibernate.cache.Cache; 21 | import org.hibernate.cache.CacheException; 22 | import org.hibernate.cache.CacheProvider; 23 | import org.hibernate.cache.Timestamper; 24 | 25 | import java.util.Properties; 26 | 27 | /** 28 | * 为 Hibernate 3 提供 J2Cache 的适配 29 | * @author liao 30 | */ 31 | @SuppressWarnings("deprecation") 32 | public class J2CacheProvider implements CacheProvider { 33 | 34 | @Override 35 | public Cache buildCache(String regionName, Properties properties) 36 | throws CacheException { 37 | return new J2HibernateCache(regionName, J2Cache.getChannel()); 38 | } 39 | 40 | @Override 41 | public boolean isMinimalPutsEnabledByDefault() { 42 | return true; 43 | } 44 | 45 | @Override 46 | public long nextTimestamp() { 47 | return Timestamper.next(); 48 | } 49 | 50 | @Override 51 | public void start(Properties properties) throws CacheException { 52 | 53 | } 54 | 55 | @Override 56 | public void stop() { 57 | J2Cache.getChannel().close(); 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /modules/hibernate3/src/net/oschina/j2cache/hibernate3/J2CacheRegionFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate3; 17 | 18 | import net.oschina.j2cache.CacheChannel; 19 | import net.oschina.j2cache.J2Cache; 20 | 21 | import org.hibernate.cache.*; 22 | import org.hibernate.cfg.Settings; 23 | 24 | import java.util.Properties; 25 | 26 | /** 27 | * J2Cache Hibernate RegionFactory implementations. 28 | * 29 | * @author winterlau 30 | */ 31 | public class J2CacheRegionFactory implements RegionFactory { 32 | 33 | private CacheChannel channel = J2Cache.getChannel(); 34 | 35 | @Override 36 | public CollectionRegion buildCollectionRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { 37 | return new J2CacheRegion.Collection(regionName, channel); 38 | } 39 | 40 | @Override 41 | public EntityRegion buildEntityRegion(String regionName, Properties properties, CacheDataDescription metadata) throws CacheException { 42 | return new J2CacheRegion.Entity(regionName, channel); 43 | } 44 | 45 | @Override 46 | public QueryResultsRegion buildQueryResultsRegion(String regionName, Properties properties) throws CacheException { 47 | return new J2CacheRegion.QueryResults(regionName, channel); 48 | } 49 | 50 | @Override 51 | public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException { 52 | return new J2CacheRegion.Timestamps(regionName, channel); 53 | } 54 | 55 | @Override 56 | public boolean isMinimalPutsEnabledByDefault() { 57 | return true; 58 | } 59 | 60 | @Override 61 | public long nextTimestamp() { 62 | return Timestamper.next(); 63 | } 64 | 65 | @Override 66 | public void start(Settings settings, Properties properties) throws CacheException { 67 | 68 | } 69 | 70 | @Override 71 | public void stop() { 72 | channel.close(); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /modules/hibernate3/test/config/User.hbm.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /modules/hibernate3/test/config/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | com.mysql.jdbc.Driver 12 | jdbc:mysql://localhost/test 13 | root 14 | 1234 15 | 16 | 17 | 18 | 19 | 20 | org.hibernate.dialect.MySQLDialect 21 | 22 | 23 | 24 | 25 | 26 | net.oschina.j2cache.hibernate.J2CacheProvider 27 | true 28 | 29 | 30 | true 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /modules/hibernate3/test/config/j2cache.properties: -------------------------------------------------------------------------------- 1 | #J2Cache configuration 2 | 3 | ######################################### 4 | # Level 1&2 provider 5 | # values: 6 | # none -> disable this level cache 7 | # ehcache -> use ehcache as level 1 cache 8 | # redis -> use redis as level 2 cache 9 | # [classname] -> use custom provider 10 | ######################################### 11 | 12 | cache.L1.provider_class=ehcache 13 | cache.L2.provider_class=redis 14 | 15 | ######################################### 16 | # Cache Serialization Provider 17 | # values: 18 | # fst -> fast-serialization 19 | # java -> java standard 20 | # [classname implements Serializer] 21 | ######################################### 22 | 23 | cache.serialization = fst 24 | 25 | ######################################### 26 | # Redis connection configuration 27 | ######################################### 28 | 29 | ## connection 30 | redis.host = localhost 31 | redis.port = 6379 32 | redis.timeout = 2000 33 | ##redis.password = 34 | redis.database = 1 35 | 36 | ## properties 37 | redis.maxActive = -1 38 | redis.maxIdle = 2000 39 | redis.maxWaitMillis = 100 40 | redis.minEvictableIdleTimeMillis = 864000000 41 | redis.minIdle = 1000 42 | redis.numTestsPerEvictionRun = 10 43 | redis.lifo = false 44 | redis.softMinEvictableIdleTimeMillis = 10 45 | redis.testOnBorrow = true 46 | redis.testOnReturn = false 47 | redis.testWhileIdle = false 48 | redis.timeBetweenEvictionRunsMillis = 300000 49 | redis.blockWhenExhausted = true 50 | 51 | -------------------------------------------------------------------------------- /modules/hibernate3/test/config/log4j.properties: -------------------------------------------------------------------------------- 1 | log4j.rootLogger=ERROR, stdout 2 | log4j.logger.net.oschina=DEBUG, stdout 3 | log4j.additivity.net.oschina=false 4 | log4j.appender.stdout=org.apache.log4j.ConsoleAppender 5 | log4j.appender.stdout.layout =org.apache.log4j.PatternLayout 6 | log4j.appender.stdout.layout.ConversionPattern =%d{yyyy-MM-dd HH:mm:ss} %5p %l - %m%n -------------------------------------------------------------------------------- /modules/hibernate3/test/config/network.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 51 | 52 | 55 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /modules/hibernate3/test/config/user.sql: -------------------------------------------------------------------------------- 1 | -- MySQL dump 10.13 Distrib 5.1.41, for debian-linux-gnu (x86_64) 2 | -- 3 | -- Host: localhost Database: test 4 | -- ------------------------------------------------------ 5 | -- Server version 5.1.41-3ubuntu12 6 | 7 | /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; 8 | /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; 9 | /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; 10 | /*!40101 SET NAMES utf8 */; 11 | /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; 12 | /*!40103 SET TIME_ZONE='+00:00' */; 13 | /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; 14 | /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; 15 | /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; 16 | /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; 17 | 18 | -- 19 | -- Table structure for table `tb_user` 20 | -- 21 | 22 | DROP TABLE IF EXISTS `tb_user`; 23 | /*!40101 SET @saved_cs_client = @@character_set_client */; 24 | /*!40101 SET character_set_client = utf8 */; 25 | CREATE TABLE `tb_user` ( 26 | `id` int(11) NOT NULL AUTO_INCREMENT, 27 | `name` varchar(20) NOT NULL, 28 | PRIMARY KEY (`id`) 29 | ) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=latin1; 30 | /*!40101 SET character_set_client = @saved_cs_client */; 31 | /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; 32 | 33 | /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; 34 | /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; 35 | /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; 36 | /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; 37 | /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; 38 | /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; 39 | /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; 40 | 41 | -- Dump completed on 2015-03-05 15:01:11 42 | -------------------------------------------------------------------------------- /modules/hibernate3/test/src/net/oschina/j2cache/hibernate3/J2CacheProviderTester.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package net.oschina.j2cache.hibernate3; 5 | 6 | import org.hibernate.Session; 7 | import org.hibernate.SessionFactory; 8 | import org.hibernate.cfg.Configuration; 9 | import org.junit.After; 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | 13 | import static org.junit.Assert.assertTrue; 14 | 15 | /** 16 | * @author liao 17 | * 18 | */ 19 | 20 | public class J2CacheProviderTester { 21 | 22 | static SessionFactory sessionFactory; 23 | 24 | static { 25 | Configuration configuration = new Configuration(); 26 | sessionFactory = configuration.configure().buildSessionFactory(); 27 | } 28 | 29 | @Before 30 | public void testInsert() { 31 | Session session = sessionFactory.openSession(); 32 | session.beginTransaction(); 33 | try { 34 | User user = new User(); 35 | user.setId(1); 36 | user.setName("tom"); 37 | session.save(user); 38 | user = (User) session.get(User.class, 1); 39 | session.getTransaction().commit(); 40 | } catch (Exception e) { 41 | e.printStackTrace(); 42 | session.getTransaction().rollback(); 43 | } finally { 44 | session.close(); 45 | } 46 | } 47 | 48 | @After 49 | public void testDelete() { 50 | Session session = sessionFactory.openSession(); 51 | session.beginTransaction(); 52 | try { 53 | User user = (User) session.get(User.class, 1); 54 | assertTrue(user != null); 55 | session.delete(user); 56 | session.getTransaction().commit(); 57 | } catch (Exception e) { 58 | e.printStackTrace(); 59 | session.getTransaction().rollback(); 60 | } finally { 61 | session.close(); 62 | } 63 | } 64 | 65 | @Test 66 | public void testQuery() { 67 | Session session = sessionFactory.openSession(); 68 | User user = (User) session.get(User.class, 1); 69 | assertTrue(user.getId() == 1); 70 | user = (User) session.get(User.class, 1); 71 | assertTrue(user.getName().equals("tom")); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /modules/hibernate3/test/src/net/oschina/j2cache/hibernate3/J2CacheRegionFactoryTest.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate3; 2 | 3 | import org.junit.After; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | public class J2CacheRegionFactoryTest { 8 | 9 | @Before 10 | public void setUp() throws Exception { 11 | 12 | } 13 | 14 | @After 15 | public void tearDown() throws Exception { 16 | 17 | } 18 | 19 | @Test 20 | public void testBuildCollectionRegion() throws Exception { 21 | 22 | } 23 | 24 | @Test 25 | public void testBuildEntityRegion() throws Exception { 26 | 27 | } 28 | 29 | @Test 30 | public void testBuildQueryResultsRegion() throws Exception { 31 | 32 | } 33 | 34 | @Test 35 | public void testBuildTimestampsRegion() throws Exception { 36 | 37 | } 38 | 39 | @Test 40 | public void testIsMinimalPutsEnabledByDefault() throws Exception { 41 | 42 | } 43 | 44 | @Test 45 | public void testNextTimestamp() throws Exception { 46 | 47 | } 48 | 49 | @Test 50 | public void testStart() throws Exception { 51 | 52 | } 53 | 54 | @Test 55 | public void testStop() throws Exception { 56 | 57 | } 58 | } -------------------------------------------------------------------------------- /modules/hibernate3/test/src/net/oschina/j2cache/hibernate3/User.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | */ 4 | package net.oschina.j2cache.hibernate3; 5 | 6 | /** 7 | * @author liao 8 | * 9 | */ 10 | public class User { 11 | 12 | private int id; 13 | 14 | private String name; 15 | 16 | public int getId() { 17 | return id; 18 | } 19 | public void setId(int id) { 20 | this.id = id; 21 | } 22 | public String getName() { 23 | return name; 24 | } 25 | public void setName(String name) { 26 | this.name = name; 27 | } 28 | @Override 29 | public String toString() { 30 | return "User [id=" + id + ", name=" + name + "]"; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /modules/hibernate4/Readme.md: -------------------------------------------------------------------------------- 1 | 对 Hibernate 4.x 的支持 -------------------------------------------------------------------------------- /modules/hibernate4/pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | net.oschina.j2cache 5 | j2cache 6 | 2.8.0-release 7 | ../../pom.xml 8 | 9 | 10 | 4.0.0 11 | j2cache-hibernate4 12 | J2Cache - hibernate4 13 | 14 | 15 | 4.3.11.Final 16 | 4.3.13.RELEASE 17 | 18 | 19 | 20 | 21 | net.oschina.j2cache 22 | j2cache-core 23 | provided 24 | 25 | 26 | org.hibernate 27 | hibernate-ehcache 28 | ${hibernate.version} 29 | compile 30 | 31 | 32 | 33 | org.springframework 34 | spring-test 35 | ${spring.version} 36 | test 37 | 38 | 39 | org.springframework 40 | spring-web 41 | ${spring.version} 42 | test 43 | 44 | 45 | org.springframework 46 | spring-context-support 47 | ${spring.version} 48 | test 49 | 50 | 51 | org.springframework 52 | spring-orm 53 | ${spring.version} 54 | test 55 | 56 | 57 | 58 | 59 | 60 | src 61 | test/src 62 | 63 | 64 | 65 | 66 | 67 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/CacheRegion.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4; 17 | 18 | import net.oschina.j2cache.CacheObject; 19 | 20 | public interface CacheRegion { 21 | 22 | String getName(); 23 | 24 | void clear(); 25 | 26 | CacheObject get(Object key); 27 | 28 | void put(Object key, Object value); 29 | 30 | void evict(Object key); 31 | 32 | Iterable keys(); 33 | 34 | } 35 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/J2CacheCacheRegion.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4; 17 | 18 | import net.oschina.j2cache.CacheChannel; 19 | import net.oschina.j2cache.CacheObject; 20 | 21 | public class J2CacheCacheRegion implements CacheRegion { 22 | 23 | private CacheChannel cacheChannel; 24 | private String region; 25 | 26 | public J2CacheCacheRegion(CacheChannel channel, String region) { 27 | this.cacheChannel = channel; 28 | this.region = region; 29 | } 30 | 31 | @Override 32 | public String getName() { 33 | return this.region; 34 | } 35 | 36 | @Override 37 | public void clear() { 38 | this.cacheChannel.clear(this.region); 39 | } 40 | 41 | @Override 42 | public CacheObject get(Object key) { 43 | return this.cacheChannel.get(this.region, key.toString()); 44 | } 45 | 46 | @Override 47 | public void put(Object key, Object value) { 48 | this.cacheChannel.set(this.region, key.toString(), value); 49 | } 50 | 51 | @Override 52 | public void evict(Object key) { 53 | this.cacheChannel.evict(this.region, key.toString()); 54 | } 55 | 56 | public Iterable keys() { 57 | return this.cacheChannel.keys(this.region); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/J2CacheRegionFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4; 17 | 18 | import net.oschina.j2cache.J2Cache; 19 | 20 | import org.hibernate.cache.CacheException; 21 | import org.hibernate.cfg.Settings; 22 | 23 | import java.util.Properties; 24 | 25 | 26 | public class J2CacheRegionFactory extends AbstractJ2CacheRegionFactory { 27 | 28 | private static final String SPRING_CACHEMANAGER = "hibernate.cache.spring.cache_manager"; 29 | 30 | private static final String DEFAULT_SPRING_CACHEMANAGER = "cacheManager"; 31 | 32 | @SuppressWarnings("UnusedDeclaration") 33 | public J2CacheRegionFactory() { 34 | } 35 | 36 | @SuppressWarnings("UnusedDeclaration") 37 | public J2CacheRegionFactory(Properties prop) { 38 | super(); 39 | } 40 | 41 | @Override 42 | public void start(Settings settings, Properties properties) throws CacheException { 43 | this.settings = settings; 44 | if (this.channel == null) { 45 | this.channel = J2Cache.getChannel(); 46 | } 47 | } 48 | 49 | @Override 50 | public void stop() { 51 | if (channel != null) { 52 | channel.close(); 53 | } 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/nonstop/HibernateNonstopCacheExceptionHandler.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.nonstop; 17 | 18 | import net.oschina.j2cache.hibernate4.log.J2CacheMessageLogger; 19 | import org.jboss.logging.Logger; 20 | 21 | public final class HibernateNonstopCacheExceptionHandler { 22 | public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "J2Cache.hibernate.propagateNonStopCacheException"; 23 | public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "J2Cache.hibernate.logNonStopCacheExceptionStackTrace"; 24 | 25 | private static final J2CacheMessageLogger LOG = Logger.getMessageLogger(J2CacheMessageLogger.class, HibernateNonstopCacheExceptionHandler.class.getName()); 26 | private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler(); 27 | 28 | private HibernateNonstopCacheExceptionHandler() { 29 | } 30 | 31 | public static HibernateNonstopCacheExceptionHandler getInstance() { 32 | return INSTANCE; 33 | } 34 | 35 | public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) { 36 | if (Boolean.getBoolean(HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY)) { 37 | throw nonStopCacheException; 38 | } else { 39 | if (Boolean.getBoolean(HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY)) { 40 | LOG.debug("Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(), nonStopCacheException); 41 | } else { 42 | LOG.debug("Ignoring NonstopCacheException - " + nonStopCacheException.getMessage()); 43 | } 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/nonstop/NonStopCacheException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.nonstop; 17 | 18 | import org.hibernate.cache.CacheException; 19 | 20 | public class NonStopCacheException extends CacheException { 21 | 22 | public NonStopCacheException(final String message, final Throwable cause) { 23 | super(message, cause); 24 | } 25 | 26 | public NonStopCacheException(final String message) { 27 | super(message); 28 | } 29 | 30 | public NonStopCacheException(final Throwable cause) { 31 | super(cause); 32 | } 33 | 34 | } -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/regions/J2CacheCollectionRegion.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.regions; 17 | 18 | import net.oschina.j2cache.hibernate4.CacheRegion; 19 | import net.oschina.j2cache.hibernate4.strategy.J2CacheAccessStrategyFactory; 20 | import org.hibernate.cache.CacheException; 21 | import org.hibernate.cache.spi.CacheDataDescription; 22 | import org.hibernate.cache.spi.CollectionRegion; 23 | import org.hibernate.cache.spi.access.AccessType; 24 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 25 | import org.hibernate.cfg.Settings; 26 | 27 | import java.util.Properties; 28 | 29 | public class J2CacheCollectionRegion extends J2CacheTransactionalDataRegion implements CollectionRegion { 30 | 31 | public J2CacheCollectionRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, Settings settings, CacheDataDescription metadata, Properties properties) { 32 | super(accessStrategyFactory, underlyingCache, settings, metadata, properties); 33 | } 34 | 35 | @Override 36 | public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { 37 | return getAccessStrategyFactory().createCollectionRegionAccessStrategy(this, accessType); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/regions/J2CacheEntityRegion.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.regions; 17 | 18 | import net.oschina.j2cache.hibernate4.CacheRegion; 19 | import net.oschina.j2cache.hibernate4.strategy.J2CacheAccessStrategyFactory; 20 | import org.hibernate.cache.CacheException; 21 | import org.hibernate.cache.spi.CacheDataDescription; 22 | import org.hibernate.cache.spi.EntityRegion; 23 | import org.hibernate.cache.spi.access.AccessType; 24 | import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; 25 | import org.hibernate.cfg.Settings; 26 | 27 | import java.util.Properties; 28 | 29 | public class J2CacheEntityRegion extends J2CacheTransactionalDataRegion implements EntityRegion { 30 | 31 | public J2CacheEntityRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, Settings settings, CacheDataDescription metadata, Properties properties) { 32 | super(accessStrategyFactory,underlyingCache, settings, metadata, properties); 33 | } 34 | 35 | @Override 36 | public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { 37 | return getAccessStrategyFactory().createEntityRegionAccessStrategy( this, accessType ); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/regions/J2CacheNaturalIdRegion.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.regions; 17 | 18 | import net.oschina.j2cache.hibernate4.CacheRegion; 19 | import net.oschina.j2cache.hibernate4.strategy.J2CacheAccessStrategyFactory; 20 | import org.hibernate.cache.CacheException; 21 | import org.hibernate.cache.spi.CacheDataDescription; 22 | import org.hibernate.cache.spi.NaturalIdRegion; 23 | import org.hibernate.cache.spi.access.AccessType; 24 | import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; 25 | import org.hibernate.cfg.Settings; 26 | 27 | import java.util.Properties; 28 | 29 | public class J2CacheNaturalIdRegion extends J2CacheTransactionalDataRegion implements NaturalIdRegion { 30 | 31 | public J2CacheNaturalIdRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, Settings settings, CacheDataDescription metadata, Properties properties) { 32 | super(accessStrategyFactory, underlyingCache, settings, metadata, properties); 33 | } 34 | 35 | @Override 36 | public NaturalIdRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { 37 | return getAccessStrategyFactory().createNaturalIdRegionAccessStrategy(this, accessType); 38 | } 39 | } -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/regions/J2CacheQueryResultsRegion.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.regions; 17 | 18 | import net.oschina.j2cache.hibernate4.CacheRegion; 19 | import net.oschina.j2cache.hibernate4.strategy.J2CacheAccessStrategyFactory; 20 | import org.hibernate.cache.spi.QueryResultsRegion; 21 | 22 | import java.util.Properties; 23 | 24 | public class J2CacheQueryResultsRegion extends J2CacheGeneralDataRegion implements QueryResultsRegion { 25 | 26 | public J2CacheQueryResultsRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, Properties properties) { 27 | super( accessStrategyFactory, underlyingCache, properties ); 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/regions/J2CacheTimestampsRegion.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.regions; 17 | 18 | import net.oschina.j2cache.hibernate4.CacheRegion; 19 | import net.oschina.j2cache.hibernate4.strategy.J2CacheAccessStrategyFactory; 20 | import org.hibernate.cache.spi.TimestampsRegion; 21 | 22 | import java.util.Properties; 23 | 24 | public class J2CacheTimestampsRegion extends J2CacheGeneralDataRegion implements TimestampsRegion { 25 | 26 | public J2CacheTimestampsRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, Properties properties) { 27 | super(accessStrategyFactory, underlyingCache, properties); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/strategy/AbstractJ2CacheAccessStrategy.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.strategy; 17 | 18 | import net.oschina.j2cache.hibernate4.regions.J2CacheTransactionalDataRegion; 19 | import org.hibernate.cache.CacheException; 20 | import org.hibernate.cache.spi.access.SoftLock; 21 | import org.hibernate.cfg.Settings; 22 | 23 | 24 | abstract class AbstractJ2CacheAccessStrategy { 25 | 26 | private final T region; 27 | private final Settings settings; 28 | 29 | AbstractJ2CacheAccessStrategy(T region, Settings settings) { 30 | this.region = region; 31 | this.settings = settings; 32 | } 33 | 34 | protected T region() { 35 | return region; 36 | } 37 | 38 | protected Settings settings() { 39 | return settings; 40 | } 41 | 42 | public final boolean putFromLoad(Object key, Object value, long txTimestamp, Object version) throws CacheException { 43 | return putFromLoad( key, value, txTimestamp, version, settings.isMinimalPutsEnabled() ); 44 | } 45 | 46 | public abstract boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) 47 | throws CacheException; 48 | 49 | public final SoftLock lockRegion() { 50 | return null; 51 | } 52 | 53 | public final void unlockRegion(SoftLock lock) throws CacheException { 54 | region.clear(); 55 | } 56 | 57 | public void remove(Object key) throws CacheException { 58 | } 59 | 60 | public final void removeAll() throws CacheException { 61 | region.clear(); 62 | } 63 | 64 | public final void evict(Object key) throws CacheException { 65 | region.remove( key ); 66 | } 67 | 68 | public final void evictAll() throws CacheException { 69 | region.clear(); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/strategy/J2CacheAccessStrategyFactory.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.strategy; 17 | 18 | import net.oschina.j2cache.hibernate4.regions.J2CacheCollectionRegion; 19 | import net.oschina.j2cache.hibernate4.regions.J2CacheEntityRegion; 20 | import net.oschina.j2cache.hibernate4.regions.J2CacheNaturalIdRegion; 21 | import org.hibernate.cache.spi.access.AccessType; 22 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 23 | import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; 24 | import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; 25 | 26 | public interface J2CacheAccessStrategyFactory { 27 | 28 | EntityRegionAccessStrategy createEntityRegionAccessStrategy(J2CacheEntityRegion entityRegion, AccessType accessType); 29 | 30 | CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(J2CacheCollectionRegion collectionRegion, AccessType accessType); 31 | 32 | NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(J2CacheNaturalIdRegion naturalIdRegion, AccessType accessType); 33 | 34 | } 35 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/strategy/NonStrictReadWriteJ2CacheCollectionRegionAccessStrategy.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.strategy; 17 | 18 | import net.oschina.j2cache.hibernate4.regions.J2CacheCollectionRegion; 19 | import org.hibernate.cache.CacheException; 20 | import org.hibernate.cache.spi.CollectionRegion; 21 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 22 | import org.hibernate.cache.spi.access.SoftLock; 23 | import org.hibernate.cfg.Settings; 24 | 25 | 26 | public class NonStrictReadWriteJ2CacheCollectionRegionAccessStrategy extends AbstractJ2CacheAccessStrategy implements CollectionRegionAccessStrategy { 27 | 28 | public NonStrictReadWriteJ2CacheCollectionRegionAccessStrategy(J2CacheCollectionRegion region, Settings settings) { 29 | super(region, settings); 30 | } 31 | 32 | @Override 33 | public CollectionRegion getRegion() { 34 | return region(); 35 | } 36 | 37 | @Override 38 | public Object get(Object key, long txTimestamp) throws CacheException { 39 | return region().get(key); 40 | } 41 | 42 | @Override 43 | public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) 44 | throws CacheException { 45 | if (minimalPutOverride && region().contains(key)) { 46 | return false; 47 | } else { 48 | region().put(key, value); 49 | return true; 50 | } 51 | } 52 | 53 | @Override 54 | public SoftLock lockItem(Object key, Object version) throws CacheException { 55 | return null; 56 | } 57 | 58 | @Override 59 | public void unlockItem(Object key, SoftLock lock) throws CacheException { 60 | region().remove(key); 61 | } 62 | 63 | @Override 64 | public void remove(Object key) throws CacheException { 65 | region().remove(key); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/strategy/ReadOnlyJ2CacheCollectionRegionAccessStrategy.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.strategy; 17 | 18 | 19 | import net.oschina.j2cache.hibernate4.regions.J2CacheCollectionRegion; 20 | import org.hibernate.cache.CacheException; 21 | import org.hibernate.cache.spi.CollectionRegion; 22 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 23 | import org.hibernate.cache.spi.access.SoftLock; 24 | import org.hibernate.cfg.Settings; 25 | 26 | public class ReadOnlyJ2CacheCollectionRegionAccessStrategy extends AbstractJ2CacheAccessStrategy implements CollectionRegionAccessStrategy { 27 | 28 | public ReadOnlyJ2CacheCollectionRegionAccessStrategy(J2CacheCollectionRegion region, Settings settings) { 29 | super(region, settings); 30 | } 31 | 32 | @Override 33 | public CollectionRegion getRegion() { 34 | return region(); 35 | } 36 | 37 | @Override 38 | public Object get(Object key, long txTimestamp) throws CacheException { 39 | return region().get(key); 40 | } 41 | 42 | @Override 43 | public boolean putFromLoad(Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { 44 | if (minimalPutOverride && region().contains(key)) { 45 | return false; 46 | } else { 47 | region().put(key, value); 48 | return true; 49 | } 50 | } 51 | 52 | @Override 53 | public SoftLock lockItem(Object key, Object version) throws UnsupportedOperationException { 54 | return null; 55 | } 56 | 57 | @Override 58 | public void unlockItem(Object key, SoftLock lock) throws CacheException { 59 | } 60 | 61 | } -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/strategy/ReadWriteJ2CacheCollectionRegionAccessStrategy.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.strategy; 17 | 18 | 19 | import net.oschina.j2cache.hibernate4.regions.J2CacheCollectionRegion; 20 | import org.hibernate.cache.spi.CollectionRegion; 21 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 22 | import org.hibernate.cfg.Settings; 23 | 24 | public class ReadWriteJ2CacheCollectionRegionAccessStrategy extends AbstractReadWriteJ2CacheAccessStrategy implements CollectionRegionAccessStrategy { 25 | 26 | public ReadWriteJ2CacheCollectionRegionAccessStrategy(J2CacheCollectionRegion region, Settings settings) { 27 | super(region, settings); 28 | } 29 | 30 | @Override 31 | public CollectionRegion getRegion() { 32 | return region(); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /modules/hibernate4/src/net/oschina/j2cache/hibernate4/util/TimeProviderLoader.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017. 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.hibernate4.util; 17 | 18 | final class TimeProviderLoader { 19 | 20 | private static SlewClock.TimeProvider timeProvider = new SlewClock.TimeProvider() { 21 | public final long currentTimeMillis() { 22 | return System.currentTimeMillis(); 23 | } 24 | }; 25 | 26 | private TimeProviderLoader() { 27 | } 28 | 29 | public static synchronized SlewClock.TimeProvider getTimeProvider() { 30 | return timeProvider; 31 | } 32 | 33 | public static synchronized void setTimeProvider(final SlewClock.TimeProvider timeProvider) { 34 | TimeProviderLoader.timeProvider = timeProvider; 35 | } 36 | } -------------------------------------------------------------------------------- /modules/hibernate4/test/config/commons-logging.properties: -------------------------------------------------------------------------------- 1 | #\u8be5\u6587\u4ef6WAS\u73af\u5883\u5fc5\u987b\u5b58\u5728,\u5426\u5219\u65e5\u5fd7\u4e0d\u4f1a\u8f93\u51fa 2 | org.apache.cmmons.logging.LogFactory = org.apache.commons.logging.impl.LogFactoryImpl 3 | org.apache.commons.logging.Log = org.apache.commons.logging.impl.Log4JLogger -------------------------------------------------------------------------------- /modules/hibernate4/test/config/j2cache.properties: -------------------------------------------------------------------------------- 1 | #J2Cache configuration 2 | 3 | ######################################### 4 | # Level 1&2 provider 5 | # values: 6 | # none -> disable this level cache 7 | # ehcache -> use ehcache as level 1 cache 8 | # redis -> use redis as level 2 cache 9 | # [classname] -> use custom provider 10 | ######################################### 11 | 12 | cache.L1.provider_class=ehcache 13 | cache.L2.provider_class=redis 14 | 15 | ######################################### 16 | # Cache Serialization Provider 17 | # values: 18 | # fst -> fast-serialization 19 | # java -> java standard 20 | # [classname implements Serializer] 21 | ######################################### 22 | 23 | cache.serialization = fst 24 | 25 | ######################################### 26 | # Redis connection configuration 27 | ######################################### 28 | 29 | ## connection 30 | redis.host = localhost 31 | redis.port = 6379 32 | redis.timeout = 2000 33 | ##redis.password = 34 | redis.database = 1 35 | 36 | ## properties 37 | redis.maxActive = -1 38 | redis.maxIdle = 2000 39 | redis.maxWaitMillis = 100 40 | redis.minEvictableIdleTimeMillis = 864000000 41 | redis.minIdle = 1000 42 | redis.numTestsPerEvictionRun = 10 43 | redis.lifo = false 44 | redis.softMinEvictableIdleTimeMillis = 10 45 | redis.testOnBorrow = true 46 | redis.testOnReturn = false 47 | redis.testWhileIdle = false 48 | redis.timeBetweenEvictionRunsMillis = 300000 49 | redis.blockWhenExhausted = true 50 | 51 | -------------------------------------------------------------------------------- /modules/hibernate4/test/config/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /modules/hibernate4/test/config/network.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 51 | 52 | 55 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /modules/hibernate4/test/config/props/jdbc.properties: -------------------------------------------------------------------------------- 1 | # jdbc config 2 | jdbc.driver=com.mysql.jdbc.Driver 3 | #jdbc.driver=oracle.jdbc.driver.OracleDriver 4 | #\u5F00\u53D1\u914D\u7F6E 5 | 6 | 7 | #oracle 8 | #jdbc.driverUrl=jdbc:oracle:thin:@192.168.0.200:1521:ORCL 9 | #jdbc.user=sgp 10 | #jdbc.password=sgp 11 | #jdbc.driverUrl=jdbc:mysql://sp50f83d0575d01.mysql.rds.aliyuncs.com:3306/itsm?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8 12 | 13 | #mysql 14 | #jdbc.driverUrl=jdbc:mysql://192.168.1.200:3306/webapp?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8 15 | jdbc.driverUrl=jdbc:mysql://localhost:3306/webapp?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8 16 | jdbc.user=root 17 | jdbc.password= 18 | 19 | #\u7EBF\u4E0A\u914D\u7F6E 20 | jdbc.houseKeepingSleepTime=90000 21 | jdbc.houseKeepingTestSql=select count(1) from sys_sequence 22 | jdbc.prototypeCount=5 23 | jdbc.maximumConnectionCount=100 24 | jdbc.minimumConnectionCount=20 -------------------------------------------------------------------------------- /modules/hibernate4/test/config/redis.properties: -------------------------------------------------------------------------------- 1 | # Redis settings 2 | redis.host=localhost 3 | redis.port=6379 4 | #redis.pass=java2000_wl 5 | 6 | redis.maxIdle=300 7 | redis.maxActive=600 8 | redis.maxWait=1000 9 | redis.testOnBorrow=true -------------------------------------------------------------------------------- /modules/hibernate4/test/config/spring/applicationContext-datasource.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /modules/hibernate4/test/config/spring/applicationContext-hibernate.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | org.hibernate.dialect.MySQL5Dialect 15 | true 16 | update 17 | true 18 | org.springframework.orm.hibernate4.SpringSessionContext 19 | true 20 | true 21 | 0 22 | net.oschina.j2cache.hibernate4.J2CacheRegionFactory 23 | 26 | true 27 | true 28 | 2 29 | true 30 | false 31 | true 32 | true 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /modules/hibernate4/test/config/spring/applicationContext-transaction.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /modules/hibernate4/test/config/spring/applicationContext.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /modules/hibernate4/test/src/net/oschina/j2cache/hibernate4/service/ArticleService.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate4.service; 2 | 3 | import net.oschina.j2cache.hibernate4.bean.Article; 4 | import org.hibernate.Criteria; 5 | import org.hibernate.Session; 6 | import org.hibernate.SessionFactory; 7 | import org.hibernate.criterion.Criterion; 8 | import org.springframework.stereotype.Service; 9 | 10 | import javax.annotation.Resource; 11 | import javax.transaction.Transactional; 12 | import java.util.List; 13 | 14 | @Service 15 | @Transactional 16 | public class ArticleService { 17 | 18 | @Resource 19 | private SessionFactory sessionFactory; 20 | 21 | protected Session getSession() { 22 | return this.sessionFactory.getCurrentSession(); 23 | } 24 | 25 | public void save(Article article) { 26 | getSession().saveOrUpdate(article); 27 | } 28 | 29 | public List

find(Criterion... criterions) { 30 | Criteria criteria = getSession().createCriteria(Article.class); 31 | for (Criterion c : criterions) { 32 | criteria.add(c); 33 | } 34 | criteria.setCacheable(true); 35 | return criteria.list(); 36 | } 37 | 38 | public void delete(String id) { 39 | getSession().delete(getSession().get(Article.class, id)); 40 | } 41 | 42 | public Article findUnique(Criterion... criterions) { 43 | Criteria criteria = getSession().createCriteria(Article.class); 44 | for (Criterion c : criterions) { 45 | criteria.add(c); 46 | } 47 | criteria.setCacheable(true); 48 | return (Article)criteria.uniqueResult(); 49 | } 50 | 51 | public Article get(String id) { 52 | return (Article)getSession().get(Article.class,id); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /modules/hibernate5/readme.md: -------------------------------------------------------------------------------- 1 | # Hibernate 5 支持模块 2 | 3 | 基于 Hibernate 5.2.17 开发,感谢 [@tandy](https://gitee.com/tandy) 4 | 5 | Maven: 6 | 7 | ```xml 8 | 9 | net.oschina.j2cache 10 | j2cache-hibernate5 11 | 1.0.0-beta1 12 | 13 | ``` 14 | 使用说明: 15 | 16 | 1、XML文件配置 17 | 18 | ```xml 19 | 20 | 21 | 22 | ...省略其他配置... 23 | org.springframework.orm.hibernate5.SpringSessionContext 24 | net.oschina.j2cache.hibernate5.J2CacheRegionFactory 25 | true 26 | true 27 | 28 | 29 | ...省略其他配置... 30 | 31 | ``` 32 | 33 | 2、properties文件配置 34 | ```xml 35 | spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext 36 | spring.jpa.properties.hibernate.cache.region.factory_class=net.oschina.j2cache.hibernate5.J2CacheRegionFactory 37 | spring.jpa.properties.hibernate.cache.use_second_level_cache=true 38 | spring.jpa.properties.hibernate.cache.use_query_cache=true 39 | ``` 40 | 41 | 3、yml文件配置 42 | ```xml 43 | spring: 44 | jpa: 45 | properties: 46 | hibernate: 47 | current_session_context_class: org.springframework.orm.hibernate5.SpringSessionContext 48 | cache: 49 | use_second_level_cache: true 50 | use_query_cache: true 51 | region: 52 | factory_class: net.oschina.j2cache.hibernate5.J2CacheRegionFactory 53 | ``` -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/CacheRegion.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5; 2 | 3 | import net.oschina.j2cache.CacheObject; 4 | 5 | public interface CacheRegion { 6 | 7 | String getName(); 8 | 9 | void clear(); 10 | 11 | CacheObject get(Object key); 12 | 13 | void put(Object key, Object value); 14 | 15 | void evict(Object key); 16 | 17 | Iterable keys(); 18 | } 19 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/J2CacheCacheRegion.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5; 2 | 3 | import net.oschina.j2cache.CacheChannel; 4 | import net.oschina.j2cache.CacheObject; 5 | 6 | public class J2CacheCacheRegion implements CacheRegion { 7 | 8 | private CacheChannel cacheChannel; 9 | private String region; 10 | 11 | public J2CacheCacheRegion(CacheChannel channel, String region) { 12 | this.cacheChannel = channel; 13 | this.region = region; 14 | } 15 | 16 | @Override 17 | public String getName() { 18 | return this.region; 19 | } 20 | 21 | @Override 22 | public void clear() { 23 | this.cacheChannel.clear(this.region); 24 | } 25 | 26 | @Override 27 | public CacheObject get(Object key) { 28 | return this.cacheChannel.get(this.region, key.toString()); 29 | } 30 | 31 | @Override 32 | public void put(Object key, Object value) { 33 | this.cacheChannel.set(this.region, key.toString(), value); 34 | } 35 | 36 | @Override 37 | public void evict(Object key) { 38 | this.cacheChannel.evict(this.region, key.toString()); 39 | } 40 | 41 | public Iterable keys() { 42 | return this.cacheChannel.keys(this.region); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/J2CacheRegionFactory.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5; 2 | 3 | import net.oschina.j2cache.J2Cache; 4 | import org.hibernate.boot.spi.SessionFactoryOptions; 5 | import org.hibernate.cache.CacheException; 6 | 7 | import java.util.Map; 8 | import java.util.Properties; 9 | 10 | public class J2CacheRegionFactory extends AbstractJ2CacheRegionFactory { 11 | 12 | private static final String SPRING_CACHEMANAGER = "hibernate.cache.spring.cache_manager"; 13 | 14 | private static final String DEFAULT_SPRING_CACHEMANAGER = "cacheManager"; 15 | 16 | @SuppressWarnings("UnusedDeclaration") 17 | public J2CacheRegionFactory() { 18 | } 19 | 20 | @SuppressWarnings("UnusedDeclaration") 21 | public J2CacheRegionFactory(Properties prop) { 22 | super(); 23 | } 24 | 25 | @Override 26 | public void start(SessionFactoryOptions settings, Properties properties) throws CacheException { 27 | this.settings = settings; 28 | if (this.channel == null) { 29 | this.channel = J2Cache.getChannel(); 30 | } 31 | } 32 | 33 | @Override 34 | public void stop() { 35 | if (channel != null) { 36 | channel.close(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/nonstop/HibernateNonstopCacheExceptionHandler.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.nonstop; 2 | 3 | import net.oschina.j2cache.hibernate5.log.J2CacheMessageLogger; 4 | import org.jboss.logging.Logger; 5 | 6 | public final class HibernateNonstopCacheExceptionHandler { 7 | 8 | public static final String HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY = "J2Cache.hibernate.propagateNonStopCacheException"; 9 | public static final String HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY = "J2Cache.hibernate.logNonStopCacheExceptionStackTrace"; 10 | 11 | private static final J2CacheMessageLogger LOG = Logger.getMessageLogger(J2CacheMessageLogger.class, HibernateNonstopCacheExceptionHandler.class.getName()); 12 | private static final HibernateNonstopCacheExceptionHandler INSTANCE = new HibernateNonstopCacheExceptionHandler(); 13 | 14 | private HibernateNonstopCacheExceptionHandler() { 15 | } 16 | 17 | public static HibernateNonstopCacheExceptionHandler getInstance() { 18 | return INSTANCE; 19 | } 20 | 21 | public void handleNonstopCacheException(NonStopCacheException nonStopCacheException) { 22 | if (Boolean.getBoolean(HIBERNATE_THROW_EXCEPTION_ON_TIMEOUT_PROPERTY)) { 23 | throw nonStopCacheException; 24 | } else { 25 | if (Boolean.getBoolean(HIBERNATE_LOG_EXCEPTION_STACK_TRACE_PROPERTY)) { 26 | LOG.debug("Ignoring NonstopCacheException - " + nonStopCacheException.getMessage(), nonStopCacheException); 27 | } else { 28 | LOG.debug("Ignoring NonstopCacheException - " + nonStopCacheException.getMessage()); 29 | } 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/nonstop/NonStopCacheException.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.nonstop; 2 | 3 | import org.hibernate.cache.CacheException; 4 | 5 | public class NonStopCacheException extends CacheException { 6 | 7 | public NonStopCacheException(final String message, final Throwable cause) { 8 | super(message, cause); 9 | } 10 | 11 | public NonStopCacheException(final String message) { 12 | super(message); 13 | } 14 | 15 | public NonStopCacheException(final Throwable cause) { 16 | super(cause); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/regions/J2CacheCollectionRegion.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.regions; 2 | 3 | import net.oschina.j2cache.hibernate5.CacheRegion; 4 | import net.oschina.j2cache.hibernate5.strategy.J2CacheAccessStrategyFactory; 5 | import org.hibernate.boot.spi.SessionFactoryOptions; 6 | import org.hibernate.cache.CacheException; 7 | import org.hibernate.cache.spi.CacheDataDescription; 8 | import org.hibernate.cache.spi.CollectionRegion; 9 | import org.hibernate.cache.spi.access.AccessType; 10 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 11 | 12 | import java.util.Properties; 13 | 14 | public class J2CacheCollectionRegion extends J2CacheTransactionalDataRegion implements CollectionRegion { 15 | 16 | public J2CacheCollectionRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, SessionFactoryOptions settings, CacheDataDescription metadata, Properties properties) { 17 | super(accessStrategyFactory, underlyingCache, settings, metadata, properties); 18 | } 19 | 20 | @Override 21 | public CollectionRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { 22 | return this.getAccessStrategyFactory().createCollectionRegionAccessStrategy(this, accessType); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/regions/J2CacheEntityRegion.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.regions; 2 | 3 | import net.oschina.j2cache.hibernate5.CacheRegion; 4 | import net.oschina.j2cache.hibernate5.strategy.J2CacheAccessStrategyFactory; 5 | import org.hibernate.boot.spi.SessionFactoryOptions; 6 | import org.hibernate.cache.CacheException; 7 | import org.hibernate.cache.spi.CacheDataDescription; 8 | import org.hibernate.cache.spi.EntityRegion; 9 | import org.hibernate.cache.spi.access.AccessType; 10 | import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; 11 | 12 | import java.util.Properties; 13 | 14 | public class J2CacheEntityRegion extends J2CacheTransactionalDataRegion implements EntityRegion { 15 | 16 | public J2CacheEntityRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, SessionFactoryOptions settings, CacheDataDescription metadata, Properties properties) { 17 | super(accessStrategyFactory,underlyingCache, settings, metadata, properties); 18 | } 19 | 20 | @Override 21 | public EntityRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { 22 | return this.getAccessStrategyFactory().createEntityRegionAccessStrategy( this, accessType ); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/regions/J2CacheNaturalIdRegion.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.regions; 2 | 3 | import net.oschina.j2cache.hibernate5.CacheRegion; 4 | import net.oschina.j2cache.hibernate5.strategy.J2CacheAccessStrategyFactory; 5 | import org.hibernate.boot.spi.SessionFactoryOptions; 6 | import org.hibernate.cache.CacheException; 7 | import org.hibernate.cache.spi.CacheDataDescription; 8 | import org.hibernate.cache.spi.NaturalIdRegion; 9 | import org.hibernate.cache.spi.access.AccessType; 10 | import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; 11 | import org.hibernate.cfg.Settings; 12 | 13 | import java.util.Properties; 14 | 15 | public class J2CacheNaturalIdRegion extends J2CacheTransactionalDataRegion implements NaturalIdRegion { 16 | 17 | public J2CacheNaturalIdRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, SessionFactoryOptions settings, CacheDataDescription metadata, Properties properties) { 18 | super(accessStrategyFactory, underlyingCache, settings, metadata, properties); 19 | } 20 | 21 | @Override 22 | public NaturalIdRegionAccessStrategy buildAccessStrategy(AccessType accessType) throws CacheException { 23 | return getAccessStrategyFactory().createNaturalIdRegionAccessStrategy(this, accessType); 24 | } 25 | } -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/regions/J2CacheQueryResultsRegion.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.regions; 2 | 3 | import net.oschina.j2cache.hibernate5.CacheRegion; 4 | import net.oschina.j2cache.hibernate5.strategy.J2CacheAccessStrategyFactory; 5 | import org.hibernate.cache.spi.QueryResultsRegion; 6 | 7 | import java.util.Properties; 8 | 9 | public class J2CacheQueryResultsRegion extends J2CacheGeneralDataRegion implements QueryResultsRegion { 10 | 11 | public J2CacheQueryResultsRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, Properties properties) { 12 | super( accessStrategyFactory, underlyingCache, properties ); 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/regions/J2CacheTimestampsRegion.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.regions; 2 | 3 | import net.oschina.j2cache.hibernate5.CacheRegion; 4 | import net.oschina.j2cache.hibernate5.strategy.J2CacheAccessStrategyFactory; 5 | import org.hibernate.cache.spi.TimestampsRegion; 6 | 7 | import java.util.Properties; 8 | 9 | public class J2CacheTimestampsRegion extends J2CacheGeneralDataRegion implements TimestampsRegion { 10 | 11 | public J2CacheTimestampsRegion(J2CacheAccessStrategyFactory accessStrategyFactory, CacheRegion underlyingCache, Properties properties) { 12 | super(accessStrategyFactory, underlyingCache, properties); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/strategy/AbstractJ2CacheAccessStrategy.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.strategy; 2 | 3 | import net.oschina.j2cache.hibernate5.regions.J2CacheTransactionalDataRegion; 4 | import org.hibernate.boot.spi.SessionFactoryOptions; 5 | import org.hibernate.cache.CacheException; 6 | import org.hibernate.cache.spi.access.SoftLock; 7 | import org.hibernate.cfg.Settings; 8 | import org.hibernate.engine.spi.SharedSessionContractImplementor; 9 | 10 | 11 | abstract class AbstractJ2CacheAccessStrategy { 12 | 13 | private final T region; 14 | private final SessionFactoryOptions settings; 15 | 16 | AbstractJ2CacheAccessStrategy(T region, SessionFactoryOptions settings) { 17 | this.region = region; 18 | this.settings = settings; 19 | } 20 | 21 | protected T region() { 22 | return this.region; 23 | } 24 | 25 | protected SessionFactoryOptions settings() { 26 | return this.settings; 27 | } 28 | 29 | public final boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version) throws CacheException { 30 | return putFromLoad( session, key, value, txTimestamp, version, settings.isMinimalPutsEnabled() ); 31 | } 32 | 33 | public abstract boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) 34 | throws CacheException; 35 | 36 | public final SoftLock lockRegion() { 37 | return null; 38 | } 39 | 40 | public final void unlockRegion(SoftLock lock) throws CacheException { 41 | region.clear(); 42 | } 43 | 44 | public void remove(SharedSessionContractImplementor session, Object key) throws CacheException { 45 | } 46 | 47 | public final void removeAll() throws CacheException { 48 | region.clear(); 49 | } 50 | 51 | public final void evict(Object key) throws CacheException { 52 | region.remove( key ); 53 | } 54 | 55 | public final void evictAll() throws CacheException { 56 | region.clear(); 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/strategy/J2CacheAccessStrategyFactory.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.strategy; 2 | 3 | import net.oschina.j2cache.hibernate5.regions.J2CacheCollectionRegion; 4 | import net.oschina.j2cache.hibernate5.regions.J2CacheEntityRegion; 5 | import net.oschina.j2cache.hibernate5.regions.J2CacheNaturalIdRegion; 6 | import org.hibernate.cache.spi.access.AccessType; 7 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 8 | import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; 9 | import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; 10 | 11 | public interface J2CacheAccessStrategyFactory { 12 | 13 | EntityRegionAccessStrategy createEntityRegionAccessStrategy(J2CacheEntityRegion entityRegion, AccessType accessType); 14 | 15 | CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(J2CacheCollectionRegion collectionRegion, AccessType accessType); 16 | 17 | NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(J2CacheNaturalIdRegion naturalIdRegion, AccessType accessType); 18 | } 19 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/strategy/NonstopAccessStrategyFactory.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.strategy; 2 | 3 | import net.oschina.j2cache.hibernate5.nonstop.HibernateNonstopCacheExceptionHandler; 4 | import net.oschina.j2cache.hibernate5.nonstop.NonstopAwareCollectionRegionAccessStrategy; 5 | import net.oschina.j2cache.hibernate5.nonstop.NonstopAwareEntityRegionAccessStrategy; 6 | import net.oschina.j2cache.hibernate5.nonstop.NonstopAwareNaturalIdRegionAccessStrategy; 7 | import net.oschina.j2cache.hibernate5.regions.J2CacheCollectionRegion; 8 | import net.oschina.j2cache.hibernate5.regions.J2CacheEntityRegion; 9 | import net.oschina.j2cache.hibernate5.regions.J2CacheNaturalIdRegion; 10 | import net.oschina.j2cache.hibernate5.strategy.J2CacheAccessStrategyFactory; 11 | import org.hibernate.cache.spi.access.AccessType; 12 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 13 | import org.hibernate.cache.spi.access.EntityRegionAccessStrategy; 14 | import org.hibernate.cache.spi.access.NaturalIdRegionAccessStrategy; 15 | 16 | public class NonstopAccessStrategyFactory implements J2CacheAccessStrategyFactory { 17 | 18 | private final J2CacheAccessStrategyFactory actualFactory; 19 | 20 | public NonstopAccessStrategyFactory(J2CacheAccessStrategyFactory actualFactory) { 21 | this.actualFactory = actualFactory; 22 | } 23 | 24 | @Override 25 | public EntityRegionAccessStrategy createEntityRegionAccessStrategy(J2CacheEntityRegion entityRegion, AccessType accessType) { 26 | return new NonstopAwareEntityRegionAccessStrategy(this.actualFactory.createEntityRegionAccessStrategy(entityRegion, accessType), HibernateNonstopCacheExceptionHandler.getInstance()); 27 | } 28 | 29 | @Override 30 | public NaturalIdRegionAccessStrategy createNaturalIdRegionAccessStrategy(J2CacheNaturalIdRegion naturalIdRegion, AccessType accessType) { 31 | return new NonstopAwareNaturalIdRegionAccessStrategy(this.actualFactory.createNaturalIdRegionAccessStrategy(naturalIdRegion, accessType), HibernateNonstopCacheExceptionHandler.getInstance()); 32 | } 33 | 34 | @Override 35 | public CollectionRegionAccessStrategy createCollectionRegionAccessStrategy(J2CacheCollectionRegion collectionRegion, AccessType accessType) { 36 | return new NonstopAwareCollectionRegionAccessStrategy(this.actualFactory.createCollectionRegionAccessStrategy(collectionRegion, accessType ), HibernateNonstopCacheExceptionHandler.getInstance()); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/strategy/ReadOnlyJ2CacheCollectionRegionAccessStrategy.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.strategy; 2 | 3 | 4 | import net.oschina.j2cache.hibernate5.regions.J2CacheCollectionRegion; 5 | import org.hibernate.boot.spi.SessionFactoryOptions; 6 | import org.hibernate.cache.CacheException; 7 | import org.hibernate.cache.internal.DefaultCacheKeysFactory; 8 | import org.hibernate.cache.spi.CollectionRegion; 9 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 10 | import org.hibernate.cache.spi.access.SoftLock; 11 | import org.hibernate.engine.spi.SessionFactoryImplementor; 12 | import org.hibernate.engine.spi.SharedSessionContractImplementor; 13 | import org.hibernate.persister.collection.CollectionPersister; 14 | 15 | public class ReadOnlyJ2CacheCollectionRegionAccessStrategy extends AbstractJ2CacheAccessStrategy implements CollectionRegionAccessStrategy { 16 | 17 | public ReadOnlyJ2CacheCollectionRegionAccessStrategy(J2CacheCollectionRegion region, SessionFactoryOptions settings) { 18 | super(region, settings); 19 | } 20 | 21 | @Override 22 | public CollectionRegion getRegion() { 23 | return region(); 24 | } 25 | 26 | @Override 27 | public Object get(SharedSessionContractImplementor session, Object key, long txTimestamp) throws CacheException { 28 | return region().get(key); 29 | } 30 | 31 | @Override 32 | public boolean putFromLoad(SharedSessionContractImplementor session, Object key, Object value, long txTimestamp, Object version, boolean minimalPutOverride) throws CacheException { 33 | if (minimalPutOverride && region().contains(key)) { 34 | return false; 35 | } else { 36 | region().put(key, value); 37 | return true; 38 | } 39 | } 40 | 41 | @Override 42 | public SoftLock lockItem(SharedSessionContractImplementor session, Object key, Object version) throws UnsupportedOperationException { 43 | return null; 44 | } 45 | 46 | @Override 47 | public void unlockItem(SharedSessionContractImplementor session, Object key, SoftLock lock) throws CacheException { 48 | } 49 | 50 | @Override 51 | public Object generateCacheKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) { 52 | return DefaultCacheKeysFactory.staticCreateCollectionKey( id, persister, factory, tenantIdentifier ); 53 | } 54 | 55 | @Override 56 | public Object getCacheKeyId(Object cacheKey) { 57 | return DefaultCacheKeysFactory.staticGetCollectionId(cacheKey); 58 | } 59 | 60 | } -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/strategy/ReadWriteJ2CacheCollectionRegionAccessStrategy.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.strategy; 2 | 3 | 4 | import net.oschina.j2cache.hibernate5.regions.J2CacheCollectionRegion; 5 | import org.hibernate.boot.spi.SessionFactoryOptions; 6 | import org.hibernate.cache.internal.DefaultCacheKeysFactory; 7 | import org.hibernate.cache.spi.CollectionRegion; 8 | import org.hibernate.cache.spi.access.CollectionRegionAccessStrategy; 9 | import org.hibernate.engine.spi.SessionFactoryImplementor; 10 | import org.hibernate.persister.collection.CollectionPersister; 11 | 12 | public class ReadWriteJ2CacheCollectionRegionAccessStrategy extends AbstractReadWriteJ2CacheAccessStrategy implements CollectionRegionAccessStrategy { 13 | 14 | public ReadWriteJ2CacheCollectionRegionAccessStrategy(J2CacheCollectionRegion region, SessionFactoryOptions settings) { 15 | super(region, settings); 16 | } 17 | 18 | @Override 19 | public CollectionRegion getRegion() { 20 | return region(); 21 | } 22 | 23 | @Override 24 | public Object generateCacheKey(Object id, CollectionPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) { 25 | return DefaultCacheKeysFactory.staticCreateCollectionKey( id, persister, factory, tenantIdentifier ); 26 | } 27 | 28 | @Override 29 | public Object getCacheKeyId(Object cacheKey) { 30 | return DefaultCacheKeysFactory.staticGetCollectionId(cacheKey); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/util/TimeProviderLoader.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.util; 2 | 3 | import net.oschina.j2cache.hibernate5.util.SlewClock.TimeProvider; 4 | 5 | final class TimeProviderLoader { 6 | 7 | private static TimeProvider timeProvider = new TimeProvider() { 8 | public final long currentTimeMillis() { 9 | return System.currentTimeMillis(); 10 | } 11 | }; 12 | 13 | private TimeProviderLoader() { 14 | } 15 | 16 | public static synchronized TimeProvider getTimeProvider() { 17 | return timeProvider; 18 | } 19 | 20 | public static synchronized void setTimeProvider(TimeProvider timeProvider) { 21 | timeProvider = timeProvider; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /modules/hibernate5/src/net/oschina/j2cache/hibernate5/util/Timestamper.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.util; 2 | 3 | import java.util.concurrent.atomic.AtomicLong; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | public final class Timestamper { 9 | 10 | public static final int BIN_DIGITS = Integer.getInteger("net.oschina.j2cache.hibernate5.util.shift", 12); 11 | public static final int ONE_MS; 12 | private static final Logger LOG; 13 | private static final int MAX_LOG; 14 | private static final AtomicLong VALUE; 15 | private static final AtomicLong LOGGED; 16 | 17 | private Timestamper() { 18 | } 19 | 20 | public static long next() { 21 | int runs = 0; 22 | 23 | while(true) { 24 | long base = SlewClock.timeMillis() << BIN_DIGITS; 25 | long maxValue = base + (long)ONE_MS - 1L; 26 | long current = VALUE.get(); 27 | 28 | for(long update = Math.max(base, current + 1L); update < maxValue; update = Math.max(base, current + 1L)) { 29 | if (VALUE.compareAndSet(current, update)) { 30 | if (runs > 1) { 31 | log(base, "Thread spin-waits on time to pass. Looped {} times, you might want to increase -Dnet.oschina.j2cache.hibernate5.util.shift", runs); 32 | } 33 | 34 | return update; 35 | } 36 | 37 | current = VALUE.get(); 38 | } 39 | 40 | ++runs; 41 | } 42 | } 43 | 44 | private static void log(long base, String message, Object... params) { 45 | if (LOG.isInfoEnabled()) { 46 | long thisLog = (base >> BIN_DIGITS) / (long)MAX_LOG; 47 | long previousLog = LOGGED.get(); 48 | if (previousLog != thisLog && LOGGED.compareAndSet(previousLog, thisLog)) { 49 | LOG.info(message, params); 50 | } 51 | } 52 | 53 | } 54 | 55 | static { 56 | ONE_MS = 1 << BIN_DIGITS; 57 | LOG = LoggerFactory.getLogger(Timestamper.class); 58 | MAX_LOG = Integer.getInteger("net.oschina.j2cache.hibernate5.util.log.max", 1) * 1000; 59 | VALUE = new AtomicLong(); 60 | LOGGED = new AtomicLong(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /modules/hibernate5/test/config/commons-logging.properties: -------------------------------------------------------------------------------- 1 | #\u8be5\u6587\u4ef6WAS\u73af\u5883\u5fc5\u987b\u5b58\u5728,\u5426\u5219\u65e5\u5fd7\u4e0d\u4f1a\u8f93\u51fa 2 | org.apache.cmmons.logging.LogFactory = org.apache.commons.logging.impl.LogFactoryImpl 3 | org.apache.commons.logging.Log = org.apache.commons.logging.impl.Log4JLogger -------------------------------------------------------------------------------- /modules/hibernate5/test/config/ehcache3.xml: -------------------------------------------------------------------------------- 1 | 5 | 6 | 7 | 8 | java.lang.String 9 | java.io.Serializable 10 | 11 | 30 12 | 13 | 14 | 1000 15 | 100 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /modules/hibernate5/test/config/j2cache.properties: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/oschina/J2Cache/7838cabb19c44df88257561fc6f53b5d7ffbbb80/modules/hibernate5/test/config/j2cache.properties -------------------------------------------------------------------------------- /modules/hibernate5/test/config/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /modules/hibernate5/test/config/network.xml: -------------------------------------------------------------------------------- 1 | 4 | 5 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 51 | 52 | 55 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /modules/hibernate5/test/config/props/jdbc.properties: -------------------------------------------------------------------------------- 1 | # jdbc config 2 | jdbc.driver=com.mysql.jdbc.Driver 3 | #jdbc.driver=oracle.jdbc.driver.OracleDriver 4 | #\u5F00\u53D1\u914D\u7F6E 5 | 6 | 7 | #oracle 8 | #jdbc.driverUrl=jdbc:oracle:thin:@192.168.0.200:1521:ORCL 9 | #jdbc.user=sgp 10 | #jdbc.password=sgp 11 | #jdbc.driverUrl=jdbc:mysql://sp50f83d0575d01.mysql.rds.aliyuncs.com:3306/itsm?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8 12 | 13 | #mysql 14 | #jdbc.driverUrl=jdbc:mysql://192.168.1.200:3306/webapp?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8 15 | jdbc.driverUrl=jdbc:mysql://localhost:3306/webapp?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8 16 | jdbc.user=root 17 | jdbc.password=123456 18 | 19 | #\u7EBF\u4E0A\u914D\u7F6E 20 | jdbc.houseKeepingSleepTime=90000 21 | jdbc.houseKeepingTestSql=select count(1) from sys_sequence 22 | jdbc.prototypeCount=5 23 | jdbc.maximumConnectionCount=100 24 | jdbc.minimumConnectionCount=20 -------------------------------------------------------------------------------- /modules/hibernate5/test/config/redis.properties: -------------------------------------------------------------------------------- 1 | # Redis settings 2 | redis.host=localhost 3 | redis.port=6379 4 | #redis.pass=java2000_wl 5 | 6 | redis.maxIdle=300 7 | redis.maxActive=600 8 | redis.maxWait=1000 9 | redis.testOnBorrow=true -------------------------------------------------------------------------------- /modules/hibernate5/test/src/net/oschina/j2cache/hibernate5/service/ArticleService.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.service; 2 | 3 | import net.oschina.j2cache.hibernate5.bean.Article; 4 | import org.hibernate.Criteria; 5 | import org.hibernate.Session; 6 | import org.hibernate.SessionFactory; 7 | import org.hibernate.criterion.Criterion; 8 | import org.springframework.stereotype.Service; 9 | 10 | import javax.annotation.Resource; 11 | import javax.transaction.Transactional; 12 | import java.util.List; 13 | 14 | @Transactional 15 | @Service 16 | public class ArticleService implements IArticleService { 17 | 18 | @Resource 19 | private SessionFactory sessionFactory; 20 | 21 | protected Session getSession() { 22 | return this.sessionFactory.getCurrentSession(); 23 | } 24 | 25 | public void save(Article article) { 26 | getSession().saveOrUpdate(article); 27 | } 28 | 29 | public List
find(Criterion... criterions) { 30 | Criteria criteria = getSession().createCriteria(Article.class); 31 | for (Criterion c : criterions) { 32 | criteria.add(c); 33 | } 34 | criteria.setCacheable(true); 35 | return criteria.list(); 36 | } 37 | 38 | public void delete(String id) { 39 | getSession().delete(getSession().get(Article.class, id)); 40 | } 41 | 42 | public Article findUnique(Criterion... criterions) { 43 | Criteria criteria = getSession().createCriteria(Article.class); 44 | for (Criterion c : criterions) { 45 | criteria.add(c); 46 | } 47 | criteria.setCacheable(true); 48 | return (Article)criteria.uniqueResult(); 49 | } 50 | 51 | public Article get(String id) { 52 | return (Article)getSession().get(Article.class,id); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /modules/hibernate5/test/src/net/oschina/j2cache/hibernate5/service/IArticleService.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.hibernate5.service; 2 | 3 | import net.oschina.j2cache.hibernate5.bean.Article; 4 | import org.hibernate.criterion.Criterion; 5 | 6 | import java.util.List; 7 | 8 | public interface IArticleService { 9 | 10 | public void save(Article article); 11 | 12 | public List
find(Criterion... criterions); 13 | 14 | public void delete(String id); 15 | 16 | public Article findUnique(Criterion... criterions); 17 | 18 | public Article get(String id); 19 | } 20 | -------------------------------------------------------------------------------- /modules/mybatis/Readme.md: -------------------------------------------------------------------------------- 1 | 2 | # J2Cache 的 MyBatis 模块 3 | 4 | 该模块是为了让 mybatis 支持 J2Cache 二级缓存。 5 | 6 | 配置方法: 7 | 8 | `` 9 | 10 | Maven: 11 | 12 | ``` 13 | 14 | net.oschina.j2cache 15 | j2cache-mybatis 16 | 2.3.17-release 17 | 18 | ``` -------------------------------------------------------------------------------- /modules/mybatis/db.sql: -------------------------------------------------------------------------------- 1 | 2 | SET NAMES utf8; 3 | SET FOREIGN_KEY_CHECKS = 0; 4 | 5 | -- ---------------------------- 6 | -- Table structure for `blogs` 7 | -- ---------------------------- 8 | DROP TABLE IF EXISTS `blogs`; 9 | CREATE TABLE `blogs` ( 10 | `id` int(11) NOT NULL, 11 | `title` varchar(100) NOT NULL, 12 | `body` text NOT NULL, 13 | PRIMARY KEY (`id`) 14 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 15 | 16 | -- ---------------------------- 17 | -- Records of `blogs` 18 | -- ---------------------------- 19 | BEGIN; 20 | INSERT INTO `blogs` VALUES ('100', '博客标题1', '博客内容1'); 21 | COMMIT; 22 | 23 | SET FOREIGN_KEY_CHECKS = 1; 24 | -------------------------------------------------------------------------------- /modules/mybatis/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | j2cache 7 | net.oschina.j2cache 8 | 2.8.0-release 9 | ../../pom.xml 10 | 11 | 4.0.0 12 | 13 | j2cache-mybatis 14 | 15 | 16 | 17 | net.oschina.j2cache 18 | j2cache-core 19 | provided 20 | 21 | 22 | org.mybatis 23 | mybatis 24 | 3.4.6 25 | compile 26 | 27 | 28 | mysql 29 | mysql-connector-java 30 | 8.0.11 31 | true 32 | 33 | 34 | 35 | 36 | src/main/java 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /modules/mybatis/src/main/java/Blog.java: -------------------------------------------------------------------------------- 1 | import java.io.Serializable; 2 | 3 | /** 4 | * 测试 Entity 5 | */ 6 | public class Blog implements Serializable { 7 | 8 | private int id; 9 | private String title; 10 | private String body; 11 | 12 | public int getId() { 13 | return id; 14 | } 15 | 16 | public void setId(int id) { 17 | this.id = id; 18 | } 19 | 20 | public String getTitle() { 21 | return title; 22 | } 23 | 24 | public void setTitle(String title) { 25 | this.title = title; 26 | } 27 | 28 | public String getBody() { 29 | return body; 30 | } 31 | 32 | public void setBody(String body) { 33 | this.body = body; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /modules/mybatis/src/main/java/MybatisTester.java: -------------------------------------------------------------------------------- 1 | import org.apache.ibatis.session.SqlSession; 2 | import org.apache.ibatis.session.SqlSessionFactory; 3 | import org.apache.ibatis.session.SqlSessionFactoryBuilder; 4 | 5 | import java.io.InputStream; 6 | 7 | /** 8 | * 测试入口 9 | */ 10 | public class MybatisTester { 11 | 12 | public static void main(String[] args) { 13 | 14 | String resource = "/mybatis.xml"; 15 | InputStream inputStream = MybatisTester.class.getResourceAsStream(resource); 16 | SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 17 | SqlSession session = sqlSessionFactory.openSession(); 18 | try { 19 | System.out.println("mybatis init."); 20 | /* 21 | Blog blog = new Blog(); 22 | blog.setId(100); 23 | blog.setTitle("博客标题1"); 24 | blog.setBody("博客内容1"); 25 | session.insert("new", blog); 26 | 27 | System.out.println("blog inserted"); 28 | */ 29 | for(int i=0;i<10;i++) { 30 | Blog db = session.selectOne("read", 100); 31 | System.out.printf("id=%d,title=%s,body=%s%n", db.getId(), db.getTitle(), db.getBody()); 32 | session.commit(); 33 | } 34 | 35 | } catch (Exception e) { 36 | e.printStackTrace(); 37 | } finally { 38 | session.close(); 39 | System.exit(0); 40 | } 41 | 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /modules/mybatis/src/main/resources/blog.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | INSERT INTO blogs (id,title,body) VALUES(#{id},#{title},#{body}); 12 | 13 | 14 | 17 | 18 | -------------------------------------------------------------------------------- /modules/mybatis/src/main/resources/mybatis.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /modules/session-manager/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | j2cache 7 | net.oschina.j2cache 8 | 2.8.0-release 9 | ../../pom.xml 10 | 11 | 12 | 4.0.0 13 | 14 | j2cache-session-manager 15 | 1.0.0-beta4 16 | 17 | 18 | 19 | 20 | com.github.ben-manes.caffeine 21 | caffeine 22 | 2.6.2 23 | 24 | 25 | 26 | redis.clients 27 | jedis 28 | 2.9.0 29 | 30 | 31 | 32 | commons-logging 33 | commons-logging 34 | 1.2 35 | provided 36 | 37 | 38 | 39 | org.apache.commons 40 | commons-pool2 41 | 2.5.0 42 | provided 43 | 44 | 45 | 46 | javax.servlet 47 | javax.servlet-api 48 | 3.1.0 49 | provided 50 | 51 | 52 | 53 | 54 | 55 | src/main/java 56 | 57 | 58 | -------------------------------------------------------------------------------- /modules/session-manager/src/main/java/net/oschina/j2cache/session/CacheExpiredListener.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.session; 17 | 18 | /** 19 | * When cached data expired in ehcache, this listener will be invoked. 20 | * 21 | * @author Winter Lau(javayou@gmail.com) 22 | */ 23 | public interface CacheExpiredListener { 24 | 25 | void notifyElementExpired(String key) ; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /modules/session-manager/src/main/java/net/oschina/j2cache/session/CaffeineCache.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.session; 17 | 18 | import com.github.benmanes.caffeine.cache.Cache; 19 | import com.github.benmanes.caffeine.cache.Caffeine; 20 | import com.github.benmanes.caffeine.cache.RemovalCause; 21 | 22 | import java.util.concurrent.TimeUnit; 23 | 24 | /** 25 | * Caffeine cache 26 | * 27 | * @author Winter Lau(javayou@gmail.com) 28 | */ 29 | public class CaffeineCache { 30 | 31 | private Cache cache; 32 | private int size ; 33 | private int expire ; 34 | 35 | public CaffeineCache(int size, int expire, CacheExpiredListener listener) { 36 | cache = Caffeine.newBuilder() 37 | .maximumSize(size) 38 | .expireAfterAccess(expire, TimeUnit.SECONDS) 39 | .removalListener((k,v, cause) -> { 40 | //程序删除的缓存不做通知处理,因为上层已经做了处理 41 | if(cause != RemovalCause.EXPLICIT && cause != RemovalCause.REPLACED) 42 | listener.notifyElementExpired((String)k); 43 | }) 44 | .build(); 45 | 46 | this.size = size; 47 | this.expire = expire; 48 | } 49 | 50 | public Object get(String session_id) { 51 | return cache.getIfPresent(session_id); 52 | } 53 | 54 | public void put(String session_id, Object value) { 55 | cache.put(session_id, value); 56 | } 57 | 58 | public void evict(String session_id) { 59 | cache.invalidate(session_id); 60 | } 61 | 62 | public void close() { 63 | } 64 | 65 | public int getSize() { 66 | return size; 67 | } 68 | 69 | public int getExpire() { 70 | return expire; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /modules/session-manager/src/main/java/net/oschina/j2cache/session/Serializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2015-2017, Winter Lau (javayou@gmail.com). 3 | *

4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | *

8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | *

10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package net.oschina.j2cache.session; 17 | 18 | import java.io.*; 19 | 20 | /** 21 | * 对象序列化,为了确保兼容性,使用标准的 Java 序列化方法 22 | * 23 | * @author Winter Lau(javayou@gmail.com) 24 | */ 25 | public class Serializer { 26 | 27 | public static byte[] write(Object obj) throws IOException { 28 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 29 | try (ObjectOutputStream oos = new ObjectOutputStream(baos)){ 30 | oos.writeObject(obj); 31 | return baos.toByteArray(); 32 | } 33 | } 34 | 35 | public static Object read(byte[] bytes) throws IOException , ClassNotFoundException { 36 | if(bytes == null || bytes.length == 0) 37 | return null; 38 | ByteArrayInputStream bais = new ByteArrayInputStream(bytes); 39 | try (ObjectInputStream ois = new ObjectInputStream(bais)){ 40 | return ois.readObject(); 41 | } 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /modules/session-manager/test.jsp: -------------------------------------------------------------------------------- 1 | <%@ page language="java" import="javax.servlet.http.*" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> 2 | 3 | NAME: <%=session.getAttribute("name")%> 4 | 5 |

    6 |
  • Session ID: <%=session.getId()%> (<%=session.isNew()%>)
  • 7 |
  • Session IP: <%=request.getServerName()%>
  • 8 |
  • Session Port: <%=request.getServerPort()%>
  • 9 |
10 | 11 | 12 | <% 13 | session.setAttribute("name","Winter Lau"); 14 | %> -------------------------------------------------------------------------------- /modules/spring-boot-starter/readme.md: -------------------------------------------------------------------------------- 1 | 如下即可使用j2cache缓存方法 2 | ``` 3 | @Autowired 4 | private CacheChannel cacheChannel; 5 | ``` 6 | 在application.properties中支持指定j2cache配置文件,让你开发环境和生产环境分离 7 | ``` 8 | j2cache.config-location=/j2cache-${spring.profiles.active}.properties 9 | ``` 10 | 如下两项配置在application.properties,可以开启对spring cahce的支持 11 | ``` 12 | j2cache.open-spring-cache=true 13 | spring.cache.type=GENERIC 14 | ``` 15 | 如下两项配置在application.properties,可以设置spring cache是否缓存null值,默认是true 16 | ``` 17 | j2cache.allow-null-values=true 18 | ``` 19 | 20 | 如下配置在application.properties,可以选择缓存清除的模式 21 | * 缓存清除模式 22 | * active:主动清除,二级缓存过期主动通知各节点清除,优点在于所有节点可以同时收到缓存清除 23 | * passive:被动清除,一级缓存过期进行通知各节点清除一二级缓存 24 | * blend:两种模式一起运作,对于各个节点缓存准确性以及及时性要求高的可以使用(推荐使用前面两种模式中一种) 25 | ``` 26 | j2cache.cache-clean-mode=passive 27 | ``` 28 | 在j2cache.properties中配置,可以使用springRedis进行广播通知缓失效 29 | ``` 30 | j2cache.broadcast = net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy 31 | ``` 32 | 在j2cache.properties中配置,使用springRedis替换二级缓存 33 | ``` 34 | j2cache.L2.provider_class = net.oschina.j2cache.cache.support.redis.SpringRedisProvider 35 | j2cache.L2.config_section = redis 36 | ``` 37 | 在application.properties中支持关闭二级缓存 38 | ``` 39 | j2cache.l2-cache-open=false(默认开启) 40 | ``` 41 | 42 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/resources/META-INF/spring-configuration-metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties": [ 3 | { 4 | "name": "j2cache.config-location", 5 | "type": "java.lang.String" 6 | } 7 | ] 8 | } -------------------------------------------------------------------------------- /modules/spring-boot-starter/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | net.oschina.j2cache.autoconfigure.J2CacheAutoConfiguration,\ 3 | net.oschina.j2cache.autoconfigure.J2CacheSpringCacheAutoConfiguration,\ 4 | net.oschina.j2cache.autoconfigure.J2CacheSpringRedisAutoConfiguration -------------------------------------------------------------------------------- /modules/spring-boot-starter/src/net/oschina/j2cache/autoconfigure/J2CacheAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.autoconfigure; 2 | 3 | import java.io.IOException; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 7 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.context.annotation.DependsOn; 11 | import org.springframework.context.annotation.PropertySource; 12 | import org.springframework.core.env.StandardEnvironment; 13 | 14 | import net.oschina.j2cache.CacheChannel; 15 | import net.oschina.j2cache.J2Cache; 16 | import net.oschina.j2cache.J2CacheBuilder; 17 | import net.oschina.j2cache.cache.support.util.SpringJ2CacheConfigUtil; 18 | import net.oschina.j2cache.cache.support.util.SpringUtil; 19 | /** 20 | * 启动入口 21 | * @author zhangsaizz 22 | * 23 | */ 24 | @ConditionalOnClass(J2Cache.class) 25 | @EnableConfigurationProperties({J2CacheConfig.class}) 26 | @Configuration 27 | @PropertySource(value = {"${j2cache.config-location}","file:${j2cache.config-location}"},ignoreResourceNotFound = true ) 28 | public class J2CacheAutoConfiguration { 29 | 30 | @Autowired 31 | private StandardEnvironment standardEnvironment; 32 | 33 | @Bean 34 | public net.oschina.j2cache.J2CacheConfig j2CacheConfig() throws IOException{ 35 | net.oschina.j2cache.J2CacheConfig cacheConfig = new net.oschina.j2cache.J2CacheConfig(); 36 | cacheConfig = SpringJ2CacheConfigUtil.initFromConfig(standardEnvironment); 37 | return cacheConfig; 38 | } 39 | 40 | @Bean 41 | @DependsOn({"springUtil","j2CacheConfig"}) 42 | public CacheChannel cacheChannel(net.oschina.j2cache.J2CacheConfig j2CacheConfig) throws IOException { 43 | J2CacheBuilder builder = J2CacheBuilder.init(j2CacheConfig); 44 | return builder.getChannel(); 45 | } 46 | 47 | @Bean 48 | public SpringUtil springUtil() { 49 | return new SpringUtil(); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/src/net/oschina/j2cache/autoconfigure/J2CacheSpringCacheAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.autoconfigure; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.boot.autoconfigure.cache.CacheProperties; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 8 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 9 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 10 | 11 | import org.springframework.cache.annotation.EnableCaching; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | 15 | import net.oschina.j2cache.CacheChannel; 16 | import net.oschina.j2cache.J2Cache; 17 | import net.oschina.j2cache.cache.support.J2CacheCacheManger; 18 | 19 | /** 20 | * 开启对spring cache支持的配置入口 21 | * @author zhangsaizz 22 | * 23 | */ 24 | @Configuration 25 | @ConditionalOnClass(J2Cache.class) 26 | @EnableConfigurationProperties({ J2CacheConfig.class, CacheProperties.class }) 27 | @ConditionalOnProperty(name = "j2cache.open-spring-cache", havingValue = "true") 28 | @EnableCaching 29 | public class J2CacheSpringCacheAutoConfiguration { 30 | 31 | private final CacheProperties cacheProperties; 32 | 33 | private final J2CacheConfig j2CacheConfig; 34 | 35 | J2CacheSpringCacheAutoConfiguration(CacheProperties cacheProperties, J2CacheConfig j2CacheConfig) { 36 | this.cacheProperties = cacheProperties; 37 | this.j2CacheConfig = j2CacheConfig; 38 | } 39 | 40 | @Bean 41 | @ConditionalOnBean(CacheChannel.class) 42 | public J2CacheCacheManger cacheManager(CacheChannel cacheChannel) { 43 | List cacheNames = cacheProperties.getCacheNames(); 44 | J2CacheCacheManger cacheCacheManger = new J2CacheCacheManger(cacheChannel); 45 | cacheCacheManger.setAllowNullValues(j2CacheConfig.isAllowNullValues()); 46 | cacheCacheManger.setCacheNames(cacheNames); 47 | return cacheCacheManger; 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/src/net/oschina/j2cache/cache/support/J2CacheCacheManger.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support; 2 | 3 | import java.util.Collection; 4 | import java.util.Collections; 5 | import java.util.HashSet; 6 | import java.util.LinkedHashSet; 7 | import java.util.Set; 8 | 9 | import org.springframework.cache.Cache; 10 | import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager; 11 | import org.springframework.util.CollectionUtils; 12 | 13 | import net.oschina.j2cache.CacheChannel; 14 | 15 | 16 | /** 17 | * {@link Cache} implementation for J2Cache. 18 | * @author zhangsaizz 19 | * 20 | */ 21 | public class J2CacheCacheManger extends AbstractTransactionSupportingCacheManager{ 22 | 23 | private boolean allowNullValues = true; 24 | 25 | private Collection cacheNames; 26 | 27 | private boolean dynamic = true; 28 | 29 | private CacheChannel cacheChannel; 30 | 31 | public J2CacheCacheManger(CacheChannel cacheChannel){ 32 | this.cacheChannel = cacheChannel; 33 | } 34 | 35 | @Override 36 | protected Collection loadCaches() { 37 | Collection caches = new LinkedHashSet<>(cacheNames.size()); 38 | for (String name : cacheNames) { 39 | J2CacheCache cache = new J2CacheCache(name, cacheChannel, allowNullValues); 40 | caches.add(cache); 41 | } 42 | return caches; 43 | } 44 | 45 | 46 | public boolean isAllowNullValues() { 47 | return allowNullValues; 48 | } 49 | 50 | public void setAllowNullValues(boolean allowNullValues) { 51 | this.allowNullValues = allowNullValues; 52 | } 53 | 54 | @Override 55 | protected Cache getMissingCache(String name) { 56 | return this.dynamic ? new J2CacheCache(name, cacheChannel, allowNullValues) : null; 57 | } 58 | 59 | 60 | public void setCacheNames(Collection cacheNames) { 61 | Set newCacheNames = CollectionUtils.isEmpty(cacheNames) ? Collections. emptySet() 62 | : new HashSet(cacheNames); 63 | this.cacheNames = newCacheNames; 64 | this.dynamic = newCacheNames.isEmpty(); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/src/net/oschina/j2cache/cache/support/redis/ConfigureNotifyKeyspaceEventsAction.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support.redis; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.dao.InvalidDataAccessApiUsageException; 6 | import org.springframework.data.redis.connection.RedisConnection; 7 | 8 | /** 9 | * 设置redis键值回调 10 | */ 11 | public class ConfigureNotifyKeyspaceEventsAction { 12 | 13 | static final String CONFIG_NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events"; 14 | 15 | 16 | public void config(RedisConnection connection) { 17 | String notifyOptions = getNotifyOptions(connection); 18 | String customizedNotifyOptions = notifyOptions; 19 | if (!customizedNotifyOptions.contains("E")) { 20 | customizedNotifyOptions += "E"; 21 | } 22 | boolean A = customizedNotifyOptions.contains("A"); 23 | if (!(A || customizedNotifyOptions.contains("g"))) { 24 | customizedNotifyOptions += "g"; 25 | } 26 | if (!(A || customizedNotifyOptions.contains("x"))) { 27 | customizedNotifyOptions += "x"; 28 | } 29 | if (!notifyOptions.equals(customizedNotifyOptions)) { 30 | connection.setConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS, customizedNotifyOptions); 31 | } 32 | } 33 | 34 | private String getNotifyOptions(RedisConnection connection) { 35 | try { 36 | List config = connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS); 37 | if (config.size() < 2) { 38 | return ""; 39 | } 40 | return config.get(1); 41 | } 42 | catch (InvalidDataAccessApiUsageException e) { 43 | throw new IllegalStateException( 44 | "Unable to configure Redis to keyspace notifications. See http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent", 45 | e); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/src/net/oschina/j2cache/cache/support/redis/SpringRedisActiveMessageListener.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support.redis; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.data.redis.connection.Message; 6 | import org.springframework.data.redis.connection.MessageListener; 7 | 8 | import net.oschina.j2cache.cluster.ClusterPolicy; 9 | 10 | /** 11 | * 监听二缓key失效,主动清除本地缓存 12 | * 13 | * @author zhangsaizz 14 | * 15 | */ 16 | public class SpringRedisActiveMessageListener implements MessageListener { 17 | 18 | private static Logger logger = LoggerFactory.getLogger(SpringRedisActiveMessageListener.class); 19 | 20 | private ClusterPolicy clusterPolicy; 21 | 22 | private String namespace; 23 | 24 | SpringRedisActiveMessageListener(ClusterPolicy clusterPolicy, String namespace) { 25 | this.clusterPolicy = clusterPolicy; 26 | this.namespace = namespace; 27 | } 28 | 29 | @Override 30 | public void onMessage(Message message, byte[] pattern) { 31 | String key = message.toString(); 32 | if (key == null) { 33 | return; 34 | } 35 | if (key.startsWith(namespace + ":")) { 36 | String[] k = key.replaceFirst(namespace + ":", "").split(":", 2); 37 | if(k.length != 2) { 38 | return; 39 | } 40 | clusterPolicy.evict(k[0], k[1]); 41 | } 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/src/net/oschina/j2cache/cache/support/util/J2CacheSerializer.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support.util; 2 | 3 | import java.io.IOException; 4 | 5 | import org.nustaq.serialization.util.FSTUtil; 6 | import org.springframework.data.redis.serializer.RedisSerializer; 7 | import org.springframework.data.redis.serializer.SerializationException; 8 | 9 | import net.oschina.j2cache.util.SerializationUtils; 10 | 11 | 12 | public class J2CacheSerializer implements RedisSerializer{ 13 | 14 | @Override 15 | public byte[] serialize(Object t) throws SerializationException { 16 | try { 17 | return SerializationUtils.serialize(t); 18 | } catch (IOException e) { 19 | e.printStackTrace(); 20 | FSTUtil.rethrow(e); 21 | } 22 | return null; 23 | } 24 | 25 | @Override 26 | public Object deserialize(byte[] bytes) throws SerializationException { 27 | try { 28 | return SerializationUtils.deserialize(bytes); 29 | } catch (IOException e) { 30 | e.printStackTrace(); 31 | FSTUtil.rethrow(e); 32 | } 33 | return null; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/src/net/oschina/j2cache/cache/support/util/SpringJ2CacheConfigUtil.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support.util; 2 | 3 | import org.springframework.core.env.MapPropertySource; 4 | import org.springframework.core.env.StandardEnvironment; 5 | import org.springframework.core.io.support.ResourcePropertySource; 6 | 7 | import net.oschina.j2cache.J2CacheConfig; 8 | 9 | import java.util.Objects; 10 | 11 | public class SpringJ2CacheConfigUtil { 12 | 13 | /** 14 | * 从spring环境变量中查找j2cache配置 15 | * @param environment configuration 16 | * @return j2cache config instance 17 | */ 18 | public final static J2CacheConfig initFromConfig(StandardEnvironment environment){ 19 | J2CacheConfig config = new J2CacheConfig(); 20 | config.setSerialization(environment.getProperty("j2cache.serialization")); 21 | config.setBroadcast(environment.getProperty("j2cache.broadcast")); 22 | config.setL1CacheName(environment.getProperty("j2cache.L1.provider_class")); 23 | config.setL2CacheName(environment.getProperty("j2cache.L2.provider_class")); 24 | config.setSyncTtlToRedis(!"false".equalsIgnoreCase(environment.getProperty("j2cache.sync_ttl_to_redis"))); 25 | config.setDefaultCacheNullObject("true".equalsIgnoreCase(environment.getProperty("j2cache.default_cache_null_object"))); 26 | String l2_config_section = environment.getProperty("j2cache.L2.config_section"); 27 | if (l2_config_section == null || Objects.equals(l2_config_section.trim(),"")) l2_config_section = config.getL2CacheName(); 28 | final String l2_section = l2_config_section; 29 | environment.getPropertySources().forEach(a -> { 30 | if(a instanceof MapPropertySource) { 31 | MapPropertySource c = (MapPropertySource) a; 32 | c.getSource().forEach((k,v) -> { 33 | String key = k; 34 | if (key.startsWith(config.getBroadcast() + ".")) { 35 | config.getBroadcastProperties().setProperty(key.substring((config.getBroadcast() + ".").length()), 36 | environment.getProperty(key)); 37 | } 38 | if (key.startsWith(config.getL1CacheName() + ".")) { 39 | config.getL1CacheProperties().setProperty(key.substring((config.getL1CacheName() + ".").length()), 40 | environment.getProperty(key)); 41 | } 42 | if (key.startsWith(l2_section + ".")) { 43 | config.getL2CacheProperties().setProperty(key.substring((l2_section + ".").length()), 44 | environment.getProperty(key)); 45 | } 46 | }); 47 | } 48 | }); 49 | return config; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/src/net/oschina/j2cache/cache/support/util/SpringUtil.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support.util; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | 7 | /** 8 | * spring 工具类 9 | * @author zhangsaizz 10 | */ 11 | public class SpringUtil implements ApplicationContextAware { 12 | 13 | private static ApplicationContext applicationContext; 14 | 15 | /** 16 | * setApplicationContext 17 | * @param applicationContext application context 18 | * @throws BeansException exception 19 | */ 20 | @Override 21 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 22 | if (SpringUtil.applicationContext == null) { 23 | SpringUtil.applicationContext = applicationContext; 24 | } 25 | } 26 | 27 | /** 28 | * 获取applicationContext 29 | * @return ApplicationContext 30 | */ 31 | public static ApplicationContext getApplicationContext() { 32 | return applicationContext; 33 | } 34 | 35 | /** 36 | * 通过name获取 Bean. 37 | * @param name cache name 38 | * @return cache object 39 | */ 40 | public static Object getBean(String name) { 41 | return getApplicationContext().getBean(name); 42 | } 43 | 44 | public static T getBean(Class clazz) { 45 | return getApplicationContext().getBean(clazz); 46 | } 47 | 48 | public static T getBean(String name, Class clazz) { 49 | return getApplicationContext().getBean(name, clazz); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/test/src/com/test/ApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.test; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.test.context.SpringBootTest; 7 | import org.springframework.test.context.junit4.SpringRunner; 8 | import org.springframework.util.Assert; 9 | 10 | import com.test.bean.TestBean; 11 | import com.test.service.TestService; 12 | 13 | import net.oschina.j2cache.CacheChannel; 14 | import net.oschina.j2cache.CacheObject; 15 | import net.oschina.j2cache.autoconfigure.J2CacheAutoConfiguration; 16 | import net.oschina.j2cache.autoconfigure.J2CacheSpringCacheAutoConfiguration; 17 | import net.oschina.j2cache.autoconfigure.J2CacheSpringRedisAutoConfiguration; 18 | 19 | @RunWith(SpringRunner.class) 20 | @SpringBootTest(classes = { TestService.class, J2CacheAutoConfiguration.class, 21 | J2CacheSpringCacheAutoConfiguration.class, J2CacheSpringRedisAutoConfiguration.class }, properties = { 22 | "j2cache.config-location=classpath:/com/test/j2cache-test.properties", "spring.cache.type=GENERIC", 23 | "j2cache.open-spring-cache=true", "j2cache.j2CacheConfig.serialization=json" }) 24 | public class ApplicationTests { 25 | 26 | @Autowired 27 | private TestService testService; 28 | 29 | @Autowired 30 | private CacheChannel cacheChannel; 31 | 32 | @Test 33 | public void testCache() { 34 | testService.reset(); 35 | testService.evict(); 36 | testService.getNum(); 37 | Integer n = testService.getNum(); 38 | Assert.isTrue(n == 1, "缓存未生效!"); 39 | } 40 | 41 | @Test 42 | public void clearCache() { 43 | testService.reset(); 44 | testService.getNum(); 45 | testService.reset(); 46 | testService.evict(); 47 | Integer a = testService.getNum(); 48 | Assert.isTrue(a == 1, "清除缓存未生效!"); 49 | } 50 | 51 | @Test 52 | public void beanCache() { 53 | testService.reset(); 54 | testService.evict(); 55 | testService.testBean(); 56 | TestBean b = testService.testBean(); 57 | Integer a = b.getNum(); 58 | Assert.isTrue(a == 1, "对象缓存未生效!"); 59 | } 60 | 61 | @Test 62 | public void test() { 63 | cacheChannel.set("test", "123", "321"); 64 | CacheObject a = cacheChannel.get("test", "123"); 65 | Assert.isTrue(a.getValue().equals("321"), "失败!"); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/test/src/com/test/bean/TestBean.java: -------------------------------------------------------------------------------- 1 | package com.test.bean; 2 | 3 | import java.io.Serializable; 4 | 5 | public class TestBean implements Serializable{ 6 | 7 | /** 8 | * 9 | */ 10 | private static final long serialVersionUID = 1L; 11 | 12 | 13 | private Integer num; 14 | 15 | public Integer getNum() { 16 | return num; 17 | } 18 | 19 | public void setNum(Integer num) { 20 | this.num = num; 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /modules/spring-boot-starter/test/src/com/test/service/TestService.java: -------------------------------------------------------------------------------- 1 | package com.test.service; 2 | 3 | import java.util.concurrent.atomic.AtomicInteger; 4 | 5 | import org.springframework.cache.annotation.CacheEvict; 6 | import org.springframework.cache.annotation.Cacheable; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.test.bean.TestBean; 10 | 11 | @Service 12 | public class TestService { 13 | 14 | private final AtomicInteger num = new AtomicInteger(0); 15 | 16 | @Cacheable(cacheNames="test") 17 | public Integer getNum() { 18 | return num.incrementAndGet(); 19 | } 20 | 21 | @Cacheable(cacheNames="testBean") 22 | public TestBean testBean() { 23 | TestBean bean = new TestBean(); 24 | bean.setNum(num.incrementAndGet()); 25 | return bean; 26 | } 27 | 28 | @CacheEvict(cacheNames={"test","testBean"}) 29 | public void evict() { 30 | 31 | } 32 | 33 | public void reset() { 34 | num.set(0); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/readme.md: -------------------------------------------------------------------------------- 1 | 此为 spring boot2 版本!! 2 | 如下即可使用j2cache缓存方法 3 | ``` 4 | @Autowired 5 | private CacheChannel cacheChannel; 6 | ``` 7 | 在application.properties中支持指定j2cache配置文件,让你开发环境和生产环境分离 8 | ``` 9 | j2cache.config-location=/j2cache-${spring.profiles.active}.properties 10 | ``` 11 | 如下两项配置在application.properties,可以开启对spring cahce的支持 12 | ``` 13 | j2cache.open-spring-cache=true 14 | spring.cache.type=GENERIC 15 | ``` 16 | 如下两项配置在application.properties,可以设置spring cache是否缓存null值,默认是true 17 | ``` 18 | j2cache.allow-null-values=true 19 | ``` 20 | 如下配置在application.properties,可以选择缓存清除的模式 21 | * 缓存清除模式 22 | * active:主动清除,二级缓存过期主动通知各节点清除,优点在于所有节点可以同时收到缓存清除 23 | * passive:被动清除,一级缓存过期进行通知各节点清除一二级缓存 24 | * blend:两种模式一起运作,对于各个节点缓存准确性以及及时性要求高的可以使用(推荐使用前面两种模式中一种) 25 | ``` 26 | j2cache.cache-clean-mode=passive 27 | ``` 28 | 在j2cache.properties中配置,可以使用springRedis进行广播通知缓失效 29 | ``` 30 | j2cache.broadcast = net.oschina.j2cache.cache.support.redis.SpringRedisPubSubPolicy 31 | ``` 32 | 在j2cache.properties中配置,使用springRedis替换二级缓存 33 | ``` 34 | j2cache.L2.provider_class = net.oschina.j2cache.cache.support.redis.SpringRedisProvider 35 | j2cache.L2.config_section = redis (如果要使用lettuce客户端请配置为lettuce) 36 | ``` 37 | 在application.properties中支持redis客户端 38 | * jedis 39 | * lettuce 40 | ``` 41 | j2cache.redis-client=jedis 42 | ``` 43 | 在application.properties中支持关闭二级缓存 44 | ``` 45 | j2cache.l2-cache-open=false(默认开启) 46 | ``` 47 | 48 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/resources/META-INF/spring-configuration-metadata.json: -------------------------------------------------------------------------------- 1 | { 2 | "properties": [ 3 | { 4 | "name": "j2cache.config-location", 5 | "type": "java.lang.String" 6 | } 7 | ] 8 | } -------------------------------------------------------------------------------- /modules/spring-boot2-starter/resources/META-INF/spring.factories: -------------------------------------------------------------------------------- 1 | org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 2 | net.oschina.j2cache.autoconfigure.J2CacheAutoConfiguration,\ 3 | net.oschina.j2cache.autoconfigure.J2CacheSpringCacheAutoConfiguration,\ 4 | net.oschina.j2cache.autoconfigure.J2CacheSpringRedisAutoConfiguration -------------------------------------------------------------------------------- /modules/spring-boot2-starter/src/net/oschina/j2cache/autoconfigure/J2CacheAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.autoconfigure; 2 | 3 | import java.io.IOException; 4 | 5 | import org.springframework.beans.factory.annotation.Autowired; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 7 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 8 | import org.springframework.context.annotation.Bean; 9 | import org.springframework.context.annotation.Configuration; 10 | import org.springframework.context.annotation.DependsOn; 11 | import org.springframework.context.annotation.PropertySource; 12 | import org.springframework.core.env.StandardEnvironment; 13 | 14 | import net.oschina.j2cache.CacheChannel; 15 | import net.oschina.j2cache.J2Cache; 16 | import net.oschina.j2cache.J2CacheBuilder; 17 | import net.oschina.j2cache.cache.support.util.SpringJ2CacheConfigUtil; 18 | import net.oschina.j2cache.cache.support.util.SpringUtil; 19 | /** 20 | * 启动入口 21 | * @author zhangsaizz 22 | * 23 | */ 24 | @ConditionalOnClass(J2Cache.class) 25 | @EnableConfigurationProperties({J2CacheConfig.class}) 26 | @Configuration 27 | @PropertySource(value = "${j2cache.config-location}", encoding = "UTF-8", ignoreResourceNotFound = true) 28 | public class J2CacheAutoConfiguration { 29 | 30 | @Autowired 31 | private StandardEnvironment standardEnvironment; 32 | 33 | @Bean 34 | public net.oschina.j2cache.J2CacheConfig j2CacheConfig() throws IOException{ 35 | net.oschina.j2cache.J2CacheConfig cacheConfig = SpringJ2CacheConfigUtil.initFromConfig(standardEnvironment); 36 | return cacheConfig; 37 | } 38 | 39 | @Bean 40 | @DependsOn({"springUtil","j2CacheConfig"}) 41 | public CacheChannel cacheChannel(net.oschina.j2cache.J2CacheConfig j2CacheConfig) throws IOException { 42 | J2CacheBuilder builder = J2CacheBuilder.init(j2CacheConfig); 43 | return builder.getChannel(); 44 | } 45 | 46 | @Bean 47 | public SpringUtil springUtil() { 48 | return new SpringUtil(); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/src/net/oschina/j2cache/autoconfigure/J2CacheSpringCacheAutoConfiguration.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.autoconfigure; 2 | 3 | import java.util.List; 4 | 5 | import org.springframework.boot.autoconfigure.cache.CacheProperties; 6 | import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; 7 | import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; 8 | import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; 9 | import org.springframework.boot.context.properties.EnableConfigurationProperties; 10 | 11 | import org.springframework.cache.annotation.EnableCaching; 12 | import org.springframework.context.annotation.Bean; 13 | import org.springframework.context.annotation.Configuration; 14 | 15 | import net.oschina.j2cache.CacheChannel; 16 | import net.oschina.j2cache.J2Cache; 17 | import net.oschina.j2cache.cache.support.J2CacheCacheManger; 18 | 19 | /** 20 | * 开启对spring cache支持的配置入口 21 | * @author zhangsaizz 22 | * 23 | */ 24 | @Configuration 25 | @ConditionalOnClass(J2Cache.class) 26 | @EnableConfigurationProperties({ J2CacheConfig.class, CacheProperties.class }) 27 | @ConditionalOnProperty(name = "j2cache.open-spring-cache", havingValue = "true") 28 | @EnableCaching 29 | public class J2CacheSpringCacheAutoConfiguration { 30 | 31 | private final CacheProperties cacheProperties; 32 | 33 | private final J2CacheConfig j2CacheConfig; 34 | 35 | J2CacheSpringCacheAutoConfiguration(CacheProperties cacheProperties, J2CacheConfig j2CacheConfig) { 36 | this.cacheProperties = cacheProperties; 37 | this.j2CacheConfig = j2CacheConfig; 38 | } 39 | 40 | @Bean 41 | @ConditionalOnBean(CacheChannel.class) 42 | public J2CacheCacheManger cacheManager(CacheChannel cacheChannel) { 43 | List cacheNames = cacheProperties.getCacheNames(); 44 | J2CacheCacheManger cacheCacheManger = new J2CacheCacheManger(cacheChannel); 45 | cacheCacheManger.setAllowNullValues(j2CacheConfig.isAllowNullValues()); 46 | cacheCacheManger.setCacheNames(cacheNames); 47 | return cacheCacheManger; 48 | } 49 | 50 | 51 | } 52 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/src/net/oschina/j2cache/cache/support/J2CacheCacheManger.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support; 2 | 3 | import java.util.Collection; 4 | import java.util.Collections; 5 | import java.util.HashSet; 6 | import java.util.LinkedHashSet; 7 | import java.util.Set; 8 | 9 | import org.springframework.cache.Cache; 10 | import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager; 11 | import org.springframework.util.CollectionUtils; 12 | 13 | import net.oschina.j2cache.CacheChannel; 14 | 15 | 16 | /** 17 | * {@link Cache} implementation for J2Cache. 18 | * @author zhangsaizz 19 | * 20 | */ 21 | public class J2CacheCacheManger extends AbstractTransactionSupportingCacheManager{ 22 | 23 | private boolean allowNullValues = true; 24 | 25 | private Collection cacheNames; 26 | 27 | private boolean dynamic = true; 28 | 29 | private CacheChannel cacheChannel; 30 | 31 | public J2CacheCacheManger(CacheChannel cacheChannel){ 32 | this.cacheChannel = cacheChannel; 33 | } 34 | 35 | @Override 36 | protected Collection loadCaches() { 37 | Collection caches = new LinkedHashSet<>(cacheNames.size()); 38 | for (String name : cacheNames) { 39 | J2CacheCache cache = new J2CacheCache(name, cacheChannel, allowNullValues); 40 | caches.add(cache); 41 | } 42 | return caches; 43 | } 44 | 45 | 46 | public boolean isAllowNullValues() { 47 | return allowNullValues; 48 | } 49 | 50 | public void setAllowNullValues(boolean allowNullValues) { 51 | this.allowNullValues = allowNullValues; 52 | } 53 | 54 | @Override 55 | protected Cache getMissingCache(String name) { 56 | return this.dynamic ? new J2CacheCache(name, cacheChannel, allowNullValues) : null; 57 | } 58 | 59 | 60 | public void setCacheNames(Collection cacheNames) { 61 | Set newCacheNames = CollectionUtils.isEmpty(cacheNames) ? Collections. emptySet() 62 | : new HashSet(cacheNames); 63 | this.cacheNames = newCacheNames; 64 | this.dynamic = newCacheNames.isEmpty(); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/src/net/oschina/j2cache/cache/support/redis/ConfigureNotifyKeyspaceEventsAction.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support.redis; 2 | 3 | import java.util.Properties; 4 | 5 | import org.springframework.dao.InvalidDataAccessApiUsageException; 6 | import org.springframework.data.redis.connection.RedisConnection; 7 | 8 | /** 9 | * 设置redis键值回调 10 | */ 11 | public class ConfigureNotifyKeyspaceEventsAction { 12 | 13 | static final String CONFIG_NOTIFY_KEYSPACE_EVENTS = "notify-keyspace-events"; 14 | 15 | 16 | public void config(RedisConnection connection) { 17 | String notifyOptions = getNotifyOptions(connection); 18 | String customizedNotifyOptions = notifyOptions; 19 | if (!customizedNotifyOptions.contains("E")) { 20 | customizedNotifyOptions += "E"; 21 | } 22 | boolean A = customizedNotifyOptions.contains("A"); 23 | if (!(A || customizedNotifyOptions.contains("g"))) { 24 | customizedNotifyOptions += "g"; 25 | } 26 | if (!(A || customizedNotifyOptions.contains("x"))) { 27 | customizedNotifyOptions += "x"; 28 | } 29 | if (!notifyOptions.equals(customizedNotifyOptions)) { 30 | connection.setConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS, customizedNotifyOptions); 31 | } 32 | } 33 | 34 | private String getNotifyOptions(RedisConnection connection) { 35 | try { 36 | Properties config = connection.getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS); 37 | if (config.isEmpty()) { 38 | return ""; 39 | } 40 | return config.getProperty(config.stringPropertyNames().iterator().next()); 41 | } 42 | catch (InvalidDataAccessApiUsageException e) { 43 | throw new IllegalStateException( 44 | "Unable to configure Redis to keyspace notifications. See http://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisoperationssessionrepository-sessiondestroyedevent", 45 | e); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/src/net/oschina/j2cache/cache/support/redis/SpringRedisActiveMessageListener.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support.redis; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.springframework.data.redis.connection.Message; 6 | import org.springframework.data.redis.connection.MessageListener; 7 | 8 | import net.oschina.j2cache.cluster.ClusterPolicy; 9 | 10 | /** 11 | * 监听二缓key失效,主动清除本地缓存 12 | * 13 | * @author zhangsaizz 14 | * 15 | */ 16 | public class SpringRedisActiveMessageListener implements MessageListener { 17 | 18 | private static Logger logger = LoggerFactory.getLogger(SpringRedisActiveMessageListener.class); 19 | 20 | private ClusterPolicy clusterPolicy; 21 | 22 | private String namespace; 23 | 24 | SpringRedisActiveMessageListener(ClusterPolicy clusterPolicy, String namespace) { 25 | this.clusterPolicy = clusterPolicy; 26 | this.namespace = namespace; 27 | } 28 | 29 | @Override 30 | public void onMessage(Message message, byte[] pattern) { 31 | String key = message.toString(); 32 | if (key == null) { 33 | return; 34 | } 35 | if (key.startsWith(namespace + ":")) { 36 | String[] k = key.replaceFirst(namespace + ":", "").split(":", 2); 37 | if(k.length != 2) { 38 | return; 39 | } 40 | clusterPolicy.evict(k[0], k[1]); 41 | } 42 | 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/src/net/oschina/j2cache/cache/support/util/J2CacheSerializer.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support.util; 2 | 3 | import java.io.IOException; 4 | 5 | import org.springframework.data.redis.serializer.RedisSerializer; 6 | import org.springframework.data.redis.serializer.SerializationException; 7 | 8 | import net.oschina.j2cache.util.SerializationUtils; 9 | 10 | 11 | public class J2CacheSerializer implements RedisSerializer{ 12 | 13 | @Override 14 | public byte[] serialize(Object t) throws SerializationException { 15 | try { 16 | return SerializationUtils.serialize(t); 17 | } catch (IOException e) { 18 | // TODO Auto-generated catch block 19 | e.printStackTrace(); 20 | } 21 | return null; 22 | } 23 | 24 | @Override 25 | public Object deserialize(byte[] bytes) throws SerializationException { 26 | try { 27 | return SerializationUtils.deserialize(bytes); 28 | } catch (IOException e) { 29 | // TODO Auto-generated catch block 30 | e.printStackTrace(); 31 | } 32 | return null; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/src/net/oschina/j2cache/cache/support/util/SpringUtil.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.cache.support.util; 2 | 3 | import org.springframework.beans.BeansException; 4 | import org.springframework.context.ApplicationContext; 5 | import org.springframework.context.ApplicationContextAware; 6 | 7 | /** 8 | * spring 工具类 9 | * @author zhangsaizz 10 | * 11 | */ 12 | public class SpringUtil implements ApplicationContextAware { 13 | 14 | private static ApplicationContext applicationContext; 15 | 16 | @Override 17 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 18 | if (SpringUtil.applicationContext == null) { 19 | SpringUtil.applicationContext = applicationContext; 20 | } 21 | } 22 | 23 | public static ApplicationContext getApplicationContext() { 24 | return applicationContext; 25 | } 26 | 27 | public static Object getBean(String name) { 28 | return getApplicationContext().getBean(name); 29 | } 30 | 31 | public static T getBean(Class clazz) { 32 | return getApplicationContext().getBean(clazz); 33 | } 34 | 35 | public static T getBean(String name, Class clazz) { 36 | return getApplicationContext().getBean(name, clazz); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/test/src/com/test/bean/TestBean.java: -------------------------------------------------------------------------------- 1 | package com.test.bean; 2 | 3 | import java.io.Serializable; 4 | 5 | public class TestBean implements Serializable{ 6 | 7 | /** 8 | * 9 | */ 10 | private static final long serialVersionUID = 1L; 11 | 12 | 13 | private Integer num; 14 | 15 | public Integer getNum() { 16 | return num; 17 | } 18 | 19 | public void setNum(Integer num) { 20 | this.num = num; 21 | } 22 | 23 | 24 | } 25 | -------------------------------------------------------------------------------- /modules/spring-boot2-starter/test/src/com/test/service/TestService.java: -------------------------------------------------------------------------------- 1 | package com.test.service; 2 | 3 | import java.util.concurrent.atomic.AtomicInteger; 4 | 5 | import org.springframework.cache.annotation.CacheEvict; 6 | import org.springframework.cache.annotation.Cacheable; 7 | import org.springframework.stereotype.Service; 8 | 9 | import com.test.bean.TestBean; 10 | 11 | @Service 12 | public class TestService { 13 | 14 | private final AtomicInteger num = new AtomicInteger(0); 15 | 16 | @Cacheable(cacheNames="test") 17 | public Integer getNum() { 18 | return num.incrementAndGet(); 19 | } 20 | 21 | @Cacheable(cacheNames="testBean") 22 | public TestBean testBean() { 23 | TestBean bean = new TestBean(); 24 | bean.setNum(num.incrementAndGet()); 25 | return bean; 26 | } 27 | 28 | @CacheEvict(cacheNames={"test","testBean"}) 29 | public void evict() { 30 | 31 | } 32 | 33 | public void reset() { 34 | num.set(0); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /modules/springcache/j2cache-springcache.md: -------------------------------------------------------------------------------- 1 | spring cache 和 j2cache 继承示例代码,spring 配置类 2 | 3 | ```java 4 | /** 5 | * @author Chen 6 | */ 7 | @Configuration 8 | @EnableCaching 9 | public class MyCacheConfig extends CachingConfigurerSupport { 10 | @Override 11 | public CacheManager cacheManager() { 12 | // 引入配置 13 | J2CacheConfig config = J2CacheConfig.initFromConfig("/j2cache.properties"); 14 | // 生成 J2CacheBuilder 15 | J2CacheBuilder j2CacheBuilder = J2CacheBuilder.init(config); 16 | // 构建适配器 17 | J2CacheSpringCacheManageAdapter j2CacheSpringCacheManageAdapter = new J2CacheSpringCacheManageAdapter(j2CacheBuilder, true); 18 | 19 | return j2CacheSpringCacheManageAdapter; 20 | } 21 | } 22 | ``` -------------------------------------------------------------------------------- /modules/springcache/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | j2cache 7 | net.oschina.j2cache 8 | 2.8.0-release 9 | ../../pom.xml 10 | 11 | 4.0.0 12 | 13 | j2cache-springcache 14 | 15 | 16 | 17 | org.springframework 18 | spring-context-support 19 | 4.3.10.RELEASE 20 | 21 | 22 | 23 | net.oschina.j2cache 24 | j2cache-core 25 | 26 | 27 | junit 28 | junit 29 | 4.12 30 | test 31 | 32 | 33 | 34 | test/src 35 | 36 | 37 | -------------------------------------------------------------------------------- /modules/springcache/src/net/oschina/j2cache/springcache/J2CacheSpringCacheManageAdapter.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.springcache; 2 | 3 | import net.oschina.j2cache.CacheChannel; 4 | import net.oschina.j2cache.J2Cache; 5 | import net.oschina.j2cache.J2CacheBuilder; 6 | import org.springframework.cache.Cache; 7 | import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager; 8 | 9 | import java.util.Collection; 10 | 11 | /** 12 | * @author Chen 13 | */ 14 | public class J2CacheSpringCacheManageAdapter extends AbstractTransactionSupportingCacheManager { 15 | /** 16 | * Load the initial caches for this cache manager. 17 | *

Called by {@link #afterPropertiesSet()} on startup. 18 | * The returned collection may be empty but must not be {@code null}. 19 | */ 20 | @Override 21 | protected Collection loadCaches() { 22 | return null; 23 | } 24 | 25 | private J2CacheBuilder j2CacheBuilder; 26 | 27 | private boolean allowNullValues = true; 28 | 29 | /** 30 | * @param j2CacheBuilder 可选参数,不传则用 J2Cache.getChannel() 获取 CacheChannel 31 | * @param allowNullValues 默认 true 32 | */ 33 | public J2CacheSpringCacheManageAdapter(J2CacheBuilder j2CacheBuilder, boolean allowNullValues) { 34 | this.j2CacheBuilder = j2CacheBuilder; 35 | this.allowNullValues = allowNullValues; 36 | } 37 | 38 | public J2CacheSpringCacheManageAdapter() { 39 | } 40 | 41 | public J2CacheSpringCacheManageAdapter(boolean allowNullValues) { 42 | this.allowNullValues = allowNullValues; 43 | } 44 | 45 | public J2CacheSpringCacheManageAdapter(J2CacheBuilder j2CacheBuilder) { 46 | this.j2CacheBuilder = j2CacheBuilder; 47 | } 48 | 49 | 50 | @Override 51 | protected Cache getMissingCache(String name) { 52 | CacheChannel cacheChannel = j2CacheBuilder == null ? J2Cache.getChannel() : j2CacheBuilder.getChannel(); 53 | return new J2CacheSpringCacheAdapter(allowNullValues, cacheChannel, name); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /modules/springcache/test/src/net/oschina/j2cache/springcache/TestJ2CacheSpringCacheManageAdapter.java: -------------------------------------------------------------------------------- 1 | package net.oschina.j2cache.springcache; 2 | 3 | import net.oschina.j2cache.J2CacheBuilder; 4 | import net.oschina.j2cache.J2CacheConfig; 5 | import net.oschina.j2cache.util.SerializationUtils; 6 | import org.junit.Assert; 7 | import org.junit.Test; 8 | import org.springframework.cache.Cache; 9 | 10 | import java.io.IOException; 11 | 12 | public class TestJ2CacheSpringCacheManageAdapter { 13 | 14 | @Test 15 | public void testCache() throws IOException { 16 | 17 | SerializationUtils.init("fst", null); 18 | 19 | J2CacheConfig config = J2CacheConfig.initFromConfig("/j2cache.properties"); 20 | J2CacheBuilder j2CacheBuilder = J2CacheBuilder.init(config); 21 | 22 | J2CacheSpringCacheManageAdapter cacheManageAdapter = new J2CacheSpringCacheManageAdapter(j2CacheBuilder, true); 23 | String cacheName = "ddd"; 24 | Cache cache = cacheManageAdapter.getCache(cacheName); 25 | 26 | String key = "dddd"; 27 | Cache.ValueWrapper valueWrapper = cache.get(key); 28 | 29 | Assert.assertNull(valueWrapper); // 第一次取 是null 30 | 31 | cache.put(key, null); // 存 null 32 | 33 | 34 | valueWrapper = cache.get(key); 35 | Assert.assertNull(valueWrapper); //允许存 null, 存 null 之后再取 是 null 36 | cache.evict(key); // 失效 37 | valueWrapper = cache.get(key); 38 | Assert.assertNull(valueWrapper); // 失效后再取 是null 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /runtest.bat: -------------------------------------------------------------------------------- 1 | title J2Cache test 2 | mvn exec:java -pl core -------------------------------------------------------------------------------- /runtest.sh: -------------------------------------------------------------------------------- 1 | mvn exec:java -pl core --------------------------------------------------------------------------------