Allow to specify Redisson instance/config during JCache cache creation #759

pull/762/head
Nikita 8 years ago
parent 8e0cebfb5c
commit a2ba9c0681

@ -108,10 +108,12 @@ public class JCache<K, V> extends RedissonObject implements Cache<K, V> {
private CacheLoader<K, V> cacheLoader;
private CacheWriter<K, V> cacheWriter;
private boolean closed;
private boolean hasOwnRedisson;
public JCache(JCacheManager cacheManager, Redisson redisson, String name, JCacheConfiguration<K, V> config) {
public JCache(JCacheManager cacheManager, Redisson redisson, String name, JCacheConfiguration<K, V> config, boolean hasOwnRedisson) {
super(redisson.getConfig().getCodec(), redisson.getCommandExecutor(), name);
this.hasOwnRedisson = hasOwnRedisson;
this.redisson = redisson;
Factory<CacheLoader<K, V>> cacheLoaderFactory = config.getCacheLoaderFactory();
@ -2240,6 +2242,9 @@ public class JCache<K, V> extends RedissonObject implements Cache<K, V> {
synchronized (cacheManager) {
if (!isClosed()) {
if (hasOwnRedisson) {
redisson.shutdown();
}
cacheManager.closeCache(this);
for (CacheEntryListenerConfiguration<K, V> config : listeners.keySet()) {
deregisterCacheEntryListener(config);

@ -38,11 +38,12 @@ import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.jcache.bean.EmptyStatisticsMXBean;
import org.redisson.jcache.bean.JCacheManagementMXBean;
import org.redisson.jcache.bean.JCacheStatisticsMXBean;
import org.redisson.jcache.configuration.JCacheConfiguration;
import org.redisson.jcache.configuration.RedissonConfiguration;
/**
*
@ -66,7 +67,7 @@ public class JCacheManager implements CacheManager {
private final Redisson redisson;
public JCacheManager(Redisson redisson, ClassLoader classLoader, CachingProvider cacheProvider, Properties properties, URI uri) {
JCacheManager(Redisson redisson, ClassLoader classLoader, CachingProvider cacheProvider, Properties properties, URI uri) {
super();
this.classLoader = classLoader;
this.cacheProvider = cacheProvider;
@ -105,6 +106,8 @@ public class JCacheManager implements CacheManager {
public <K, V, C extends Configuration<K, V>> Cache<K, V> createCache(String cacheName, C configuration)
throws IllegalArgumentException {
checkNotClosed();
Redisson cacheRedisson = redisson;
if (cacheName == null) {
throw new NullPointerException();
}
@ -112,8 +115,23 @@ public class JCacheManager implements CacheManager {
throw new NullPointerException();
}
if (cacheRedisson == null && !(configuration instanceof RedissonConfiguration)) {
throw new IllegalStateException("Default configuration hasn't been specified!");
}
boolean hasOwnRedisson = false;
if (configuration instanceof RedissonConfiguration) {
RedissonConfiguration<K, V> rc = (RedissonConfiguration<K, V>) configuration;
if (rc.getConfig() != null) {
cacheRedisson = (Redisson) Redisson.create(rc.getConfig());
hasOwnRedisson = true;
} else {
cacheRedisson = (Redisson) rc.getRedisson();
}
}
JCacheConfiguration<K, V> cfg = new JCacheConfiguration<K, V>(configuration);
JCache<K, V> cache = new JCache<K, V>(this, redisson, cacheName, cfg);
JCache<K, V> cache = new JCache<K, V>(this, cacheRedisson, cacheName, cfg, hasOwnRedisson);
JCache<?, ?> oldCache = caches.putIfAbsent(cacheName, cache);
if (oldCache != null) {
throw new CacheException("Cache " + cacheName + " already exists");

@ -17,6 +17,8 @@ package org.redisson.jcache;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;
import java.util.Map;
import java.util.Properties;
@ -41,18 +43,14 @@ public class JCachingProvider implements CachingProvider {
private final ConcurrentMap<ClassLoader, ConcurrentMap<URI, CacheManager>> managers =
new ConcurrentHashMap<ClassLoader, ConcurrentMap<URI, CacheManager>>();
private static final String DEFAULT_URI_PATH = "jsr107-default-config";
private static URI defaulturi;
static {
try {
defaulturi = JCachingProvider.class.getResource("/redisson-jcache.json").toURI();
} catch (Exception e) {
// trying next format
try {
defaulturi = JCachingProvider.class.getResource("/redisson-jcache.yaml").toURI();
} catch (Exception e1) {
// skip
}
defaulturi = new URI(DEFAULT_URI_PATH);
} catch (URISyntaxException e) {
throw new javax.cache.CacheException(e);
}
}
@ -80,27 +78,54 @@ public class JCachingProvider implements CachingProvider {
return manager;
}
Config config = null;
try {
config = Config.fromJSON(uri.toURL());
} catch (IOException e) {
try {
config = Config.fromYAML(uri.toURL());
} catch (IOException e2) {
throw new IllegalArgumentException("Can't parse config " + uri, e2);
}
}
Config config = loadConfig(uri);
Redisson redisson = (Redisson) Redisson.create(config);
Redisson redisson = null;
if (config != null) {
redisson = (Redisson) Redisson.create(config);
}
manager = new JCacheManager(redisson, classLoader, this, properties, uri);
CacheManager oldManager = value.putIfAbsent(uri, manager);
if (oldManager != null) {
redisson.shutdown();
if (redisson != null) {
redisson.shutdown();
}
manager = oldManager;
}
return manager;
}
private Config loadConfig(URI uri) {
Config config = null;
try {
URL jsonUrl = null;
if (DEFAULT_URI_PATH.equals(uri.getPath())) {
jsonUrl = JCachingProvider.class.getResource("/redisson-jcache.json");
} else {
jsonUrl = uri.toURL();
}
if (jsonUrl == null) {
throw new IOException();
}
config = Config.fromJSON(jsonUrl);
} catch (IOException e) {
try {
URL yamlUrl = null;
if (DEFAULT_URI_PATH.equals(uri.getPath())) {
yamlUrl = JCachingProvider.class.getResource("/redisson-jcache.yaml");
} else {
yamlUrl = uri.toURL();
}
if (yamlUrl != null) {
config = Config.fromYAML(yamlUrl);
}
} catch (IOException e2) {
// skip
}
}
return config;
}
@Override
public ClassLoader getDefaultClassLoader() {
return getClass().getClassLoader();

@ -41,6 +41,10 @@ public class JCacheConfiguration<K, V> implements CompleteConfiguration<K, V> {
public JCacheConfiguration(Configuration<K, V> configuration) {
if (configuration != null) {
if (configuration instanceof RedissonConfiguration) {
configuration = ((RedissonConfiguration<K, V>)configuration).getJcacheConfig();
}
if (configuration instanceof CompleteConfiguration) {
delegate = new MutableConfiguration<K, V>((CompleteConfiguration<K, V>) configuration);
} else {

@ -0,0 +1,96 @@
/**
* Copyright 2016 Nikita Koksharov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.redisson.jcache.configuration;
import javax.cache.configuration.Configuration;
import javax.cache.configuration.MutableConfiguration;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
/**
*
* @author Nikita Koksharov
*
* @param <K> the type of key
* @param <V> the type of value
*/
public class RedissonConfiguration<K, V> implements Configuration<K, V> {
private static final long serialVersionUID = 5331107577281201157L;
private Configuration<K, V> jcacheConfig;
private Config config;
private RedissonClient redisson;
RedissonConfiguration(Config config, Configuration<K, V> jcacheConfig) {
this.config = config;
this.jcacheConfig = jcacheConfig;
}
RedissonConfiguration(RedissonClient redisson, Configuration<K, V> jcacheConfig) {
this.redisson = redisson;
this.jcacheConfig = jcacheConfig;
}
public static <K, V> Configuration<K, V> fromInstance(RedissonClient redisson) {
MutableConfiguration<K, V> config = new MutableConfiguration<K, V>();
return fromInstance(redisson, config);
}
public static <K, V> Configuration<K, V> fromInstance(RedissonClient redisson, Configuration<K, V> jcacheConfig) {
return new RedissonConfiguration<K, V>(redisson, jcacheConfig);
}
public static <K, V> Configuration<K, V> fromConfig(Config config) {
MutableConfiguration<K, V> jcacheConfig = new MutableConfiguration<K, V>();
return new RedissonConfiguration<K, V>(config, jcacheConfig);
}
public static <K, V> Configuration<K, V> fromConfig(Config config, Configuration<K, V> jcacheConfig) {
return new RedissonConfiguration<K, V>(config, jcacheConfig);
}
public Configuration<K, V> getJcacheConfig() {
return jcacheConfig;
}
public RedissonClient getRedisson() {
return redisson;
}
public Config getConfig() {
return config;
}
@Override
public Class<K> getKeyType() {
return (Class<K>) Object.class;
}
@Override
public Class<V> getValueType() {
return (Class<V>) Object.class;
}
@Override
public boolean isStoreByValue() {
return true;
}
}

@ -2,14 +2,17 @@ package org.redisson.jcache;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.cache.Cache;
import javax.cache.Caching;
import javax.cache.configuration.Configuration;
import javax.cache.configuration.FactoryBuilder;
import javax.cache.configuration.MutableCacheEntryListenerConfiguration;
import javax.cache.configuration.MutableConfiguration;
@ -22,27 +25,56 @@ import javax.cache.expiry.Duration;
import org.junit.Assert;
import org.junit.Test;
import org.redisson.BaseTest;
import org.redisson.api.RMap;
import org.redisson.RedisRunner;
import org.redisson.RedisRunner.FailedToStartRedisException;
import org.redisson.RedisRunner.RedisProcess;
import org.redisson.config.Config;
import org.redisson.jcache.configuration.RedissonConfiguration;
public class JCacheTest extends BaseTest {
@Test
public void testMapPutGet() throws InterruptedException, IllegalArgumentException, URISyntaxException {
MutableConfiguration<String, String> config = new MutableConfiguration<>();
config.setStoreByValue(true);
public void testRedissonConfig() throws InterruptedException, IllegalArgumentException, URISyntaxException, IOException {
RedisProcess runner = new RedisRunner()
.nosave()
.randomDir()
.port(6311)
.run();
URI configUri = getClass().getResource("redisson-jcache.json").toURI();
Cache<String, String> cache = Caching.getCachingProvider().getCacheManager(configUri, null)
URL configUrl = getClass().getResource("redisson-jcache.json");
Config cfg = Config.fromJSON(configUrl);
Configuration<String, String> config = RedissonConfiguration.fromConfig(cfg);
Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
.createCache("test", config);
long startTime = System.nanoTime();
cache.get("123");
long spentTime = System.nanoTime() - startTime;
System.out.println("get spentTime: " + spentTime);
cache.put("1", "2");
Assert.assertEquals("2", cache.get("1"));
cache.close();
runner.stop();
}
@Test
public void testRedissonInstance() throws InterruptedException, IllegalArgumentException, URISyntaxException {
Configuration<String, String> config = RedissonConfiguration.fromInstance(redisson);
Cache<String, String> cache = Caching.getCachingProvider().getCacheManager()
.createCache("test", config);
cache.put("1", "2");
Assert.assertEquals("2", cache.get("1"));
cache.close();
}
@Test
public void testExpiration() throws InterruptedException, IllegalArgumentException, URISyntaxException {
public void testExpiration() throws InterruptedException, IllegalArgumentException, URISyntaxException, FailedToStartRedisException, IOException {
RedisProcess runner = new RedisRunner()
.nosave()
.randomDir()
.port(6311)
.run();
MutableConfiguration<String, String> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, 1)));
config.setStoreByValue(true);
@ -65,6 +97,9 @@ public class JCacheTest extends BaseTest {
latch.await();
Assert.assertNull(cache.get(key));
cache.close();
runner.stop();
}
public static class ExpiredListener implements CacheEntryExpiredListener<String, String>, Serializable {

@ -1,5 +1,5 @@
{
"singleServerConfig":{
"address": "redis://127.0.0.1:6379"
"address": "redis://127.0.0.1:6311"
}
}
Loading…
Cancel
Save