org.springframework.cache.interceptor.KeyGenerator Java Examples

The following examples show how to use org.springframework.cache.interceptor.KeyGenerator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RedisConfig.java    From eladmin with Apache License 2.0 6 votes vote down vote up
/**
 * 自定义缓存key生成策略,默认将使用该策略
 */
@Bean
@Override
public KeyGenerator keyGenerator() {
    return (target, method, params) -> {
        Map<String,Object> container = new HashMap<>(3);
        Class<?> targetClassClass = target.getClass();
        // 类地址
        container.put("class",targetClassClass.toGenericString());
        // 方法名称
        container.put("methodName",method.getName());
        // 包名称
        container.put("package",targetClassClass.getPackage());
        // 参数列表
        for (int i = 0; i < params.length; i++) {
            container.put(String.valueOf(i),params[i]);
        }
        // 转为JSON字符串
        String jsonString = JSON.toJSONString(container);
        // 做SHA256 Hash计算,得到一个SHA256摘要作为Key
        return DigestUtils.sha256Hex(jsonString);
    };
}
 
Example #2
Source File: CachePutOperation.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public CachePutOperation(
		CacheMethodDetails<CachePut> methodDetails, CacheResolver cacheResolver, KeyGenerator keyGenerator) {

	super(methodDetails, cacheResolver, keyGenerator);

	CachePut ann = methodDetails.getCacheAnnotation();
	this.exceptionTypeFilter = createExceptionTypeFilter(ann.cacheFor(), ann.noCacheFor());

	CacheParameterDetail valueParameterDetail =
			initializeValueParameterDetail(methodDetails.getMethod(), this.allParameterDetails);
	if (valueParameterDetail == null) {
		throw new IllegalArgumentException("No parameter annotated with @CacheValue was found for " +
				methodDetails.getMethod());
	}
	this.valueParameterDetail = valueParameterDetail;
}
 
Example #3
Source File: RedisCacheConfig.java    From syhthems-platform with MIT License 6 votes vote down vote up
@Override
@Bean
public KeyGenerator keyGenerator() {
    return (target, method, params) -> {
        StringBuffer stringBuffer = new StringBuffer();
        // 获取目标的简单类名(去掉cglib动态代理的类名)
        stringBuffer.append(target.getClass().getSimpleName().replaceAll("\\$.*", ""));
        stringBuffer.append(":");
        stringBuffer.append(method.getName());
        stringBuffer.append(":");
        stringBuffer.append("(");
        String comma = "";
        for (Object obj : params) {
            stringBuffer.append(comma);
            if (obj == null) {
                stringBuffer.append("NULL");
            } else {
                stringBuffer.append(obj.toString());
            }
            comma = ",";
        }
        stringBuffer.append(")");
        return stringBuffer.toString();
    };
}
 
Example #4
Source File: KeyGeneratorAdapter.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private static Object doGenerate(KeyGenerator keyGenerator, CacheKeyInvocationContext<?> context) {
	List<Object> parameters = new ArrayList<Object>();
	for (CacheInvocationParameter param : context.getKeyParameters()) {
		Object value = param.getValue();
		if (param.getParameterPosition() == context.getAllParameters().length - 1 &&
				context.getMethod().isVarArgs()) {
			parameters.addAll((List<Object>) CollectionUtils.arrayToList(value));
		}
		else {
			parameters.add(value);
		}
	}
	return keyGenerator.generate(context.getTarget(), context.getMethod(),
			parameters.toArray(new Object[parameters.size()]));

}
 
Example #5
Source File: RedisConfig.java    From ElementVueSpringbootCodeTemplate with Apache License 2.0 6 votes vote down vote up
@Override
public KeyGenerator keyGenerator() {
	return new KeyGenerator() {
		@Override
		public Object generate(Object target, Method method, Object... params) {
			StringBuilder sb = new StringBuilder();

			sb.append(target.getClass().getSimpleName());
			sb.append('.').append(method.getName());

			// FIXME 参数太长的时候请指定key属性,否则key太长
			for (Object obj : params) {
				if (obj != null) {
					sb.append(obj.toString());
				}
			}

			return sb.toString();
		}
	};
}
 
Example #6
Source File: AnnotationJCacheOperationSource.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected CacheResultOperation createCacheResultOperation(Method method, @Nullable CacheDefaults defaults, CacheResult ann) {
	String cacheName = determineCacheName(method, defaults, ann.cacheName());
	CacheResolverFactory cacheResolverFactory =
			determineCacheResolverFactory(defaults, ann.cacheResolverFactory());
	KeyGenerator keyGenerator = determineKeyGenerator(defaults, ann.cacheKeyGenerator());

	CacheMethodDetails<CacheResult> methodDetails = createMethodDetails(method, ann, cacheName);

	CacheResolver cacheResolver = getCacheResolver(cacheResolverFactory, methodDetails);
	CacheResolver exceptionCacheResolver = null;
	final String exceptionCacheName = ann.exceptionCacheName();
	if (StringUtils.hasText(exceptionCacheName)) {
		exceptionCacheResolver = getExceptionCacheResolver(cacheResolverFactory, methodDetails);
	}

	return new CacheResultOperation(methodDetails, cacheResolver, keyGenerator, exceptionCacheResolver);
}
 
Example #7
Source File: CacheService.java    From springboot-learn with MIT License 6 votes vote down vote up
/**
 * 生产key的策略
 *
 * @return
 */

@Bean
@Override
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {

        @Override
        public Object generate(Object target, Method method, Object... params) {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        }
    };

}
 
Example #8
Source File: CachePutOperation.java    From java-technology-stack with MIT License 6 votes vote down vote up
public CachePutOperation(
		CacheMethodDetails<CachePut> methodDetails, CacheResolver cacheResolver, KeyGenerator keyGenerator) {

	super(methodDetails, cacheResolver, keyGenerator);

	CachePut ann = methodDetails.getCacheAnnotation();
	this.exceptionTypeFilter = createExceptionTypeFilter(ann.cacheFor(), ann.noCacheFor());

	CacheParameterDetail valueParameterDetail =
			initializeValueParameterDetail(methodDetails.getMethod(), this.allParameterDetails);
	if (valueParameterDetail == null) {
		throw new IllegalArgumentException("No parameter annotated with @CacheValue was found for " +
				methodDetails.getMethod());
	}
	this.valueParameterDetail = valueParameterDetail;
}
 
Example #9
Source File: RedisConfig.java    From DouBiNovel with Apache License 2.0 6 votes vote down vote up
@Override
@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            StringBuffer sb = new StringBuffer();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                //由于参数可能不同, 缓存的key也需要不一样
                sb.append(obj.toString());
            }
            return sb.toString();
        }
    };
}
 
Example #10
Source File: AnnotationJCacheOperationSource.java    From spring-analysis-note with MIT License 5 votes vote down vote up
protected CacheRemoveOperation createCacheRemoveOperation(Method method, @Nullable CacheDefaults defaults, CacheRemove ann) {
	String cacheName = determineCacheName(method, defaults, ann.cacheName());
	CacheResolverFactory cacheResolverFactory =
			determineCacheResolverFactory(defaults, ann.cacheResolverFactory());
	KeyGenerator keyGenerator = determineKeyGenerator(defaults, ann.cacheKeyGenerator());

	CacheMethodDetails<CacheRemove> methodDetails = createMethodDetails(method, ann, cacheName);
	CacheResolver cacheResolver = getCacheResolver(cacheResolverFactory, methodDetails);
	return new CacheRemoveOperation(methodDetails, cacheResolver, keyGenerator);
}
 
Example #11
Source File: RedisCacheConfig.java    From Mykit with Apache License 2.0 5 votes vote down vote up
@Bean
public KeyGenerator customKeyGenerator() {
	return new KeyGenerator() {
		@Override
		public Object generate(Object o, Method method, Object... objects) {
			StringBuilder sb = new StringBuilder();
			sb.append(o.getClass().getName());
			sb.append(method.getName());
			for (Object obj : objects) {
				sb.append(obj.toString());
			}
			return sb.toString();
		}
	};
}
 
Example #12
Source File: AnnotationJCacheOperationSource.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected CacheRemoveOperation createCacheRemoveOperation(Method method, @Nullable CacheDefaults defaults, CacheRemove ann) {
	String cacheName = determineCacheName(method, defaults, ann.cacheName());
	CacheResolverFactory cacheResolverFactory =
			determineCacheResolverFactory(defaults, ann.cacheResolverFactory());
	KeyGenerator keyGenerator = determineKeyGenerator(defaults, ann.cacheKeyGenerator());

	CacheMethodDetails<CacheRemove> methodDetails = createMethodDetails(method, ann, cacheName);
	CacheResolver cacheResolver = getCacheResolver(cacheResolverFactory, methodDetails);
	return new CacheRemoveOperation(methodDetails, cacheResolver, keyGenerator);
}
 
Example #13
Source File: KeyGeneratorAdapter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static Object doGenerate(KeyGenerator keyGenerator, CacheKeyInvocationContext<?> context) {
	List<Object> parameters = new ArrayList<>();
	for (CacheInvocationParameter param : context.getKeyParameters()) {
		Object value = param.getValue();
		if (param.getParameterPosition() == context.getAllParameters().length - 1 &&
				context.getMethod().isVarArgs()) {
			parameters.addAll((List<Object>) CollectionUtils.arrayToList(value));
		}
		else {
			parameters.add(value);
		}
	}
	return keyGenerator.generate(context.getTarget(), context.getMethod(), parameters.toArray());
}
 
Example #14
Source File: KeyGeneratorAdapter.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create an instance with the given {@link KeyGenerator} so that {@link javax.cache.annotation.CacheKey}
 * and {@link javax.cache.annotation.CacheValue} are handled according to the spec.
 */
public KeyGeneratorAdapter(JCacheOperationSource cacheOperationSource, KeyGenerator target) {
	Assert.notNull(cacheOperationSource, "JCacheOperationSource must not be null");
	Assert.notNull(target, "KeyGenerator must not be null");
	this.cacheOperationSource = cacheOperationSource;
	this.keyGenerator = target;
}
 
Example #15
Source File: RedisConfig.java    From MI-S with MIT License 5 votes vote down vote up
@Bean
public KeyGenerator wiselyKeyGenerator(){
    return (target, method, params) -> {
        StringBuilder sb = new StringBuilder();
        sb.append(target.getClass().getName());
        sb.append(method.getName());
        for (Object obj : params) {
            sb.append(obj.toString());
        }
        return sb.toString();
    };

}
 
Example #16
Source File: RedisCacheConfig.java    From agile-service-old with Apache License 2.0 5 votes vote down vote up
/**
 * redis的key生成算法重写
 */
@Bean
public KeyGenerator customKeyGenerator() {
    return (o, method, objects) -> {
        StringBuilder sb = new StringBuilder();
        sb.append(o.getClass().getName());
        sb.append(method.getName());
        for (Object obj : objects) {
            sb.append(obj.toString());
        }
        return sb.toString();
    };
}
 
Example #17
Source File: AnnotationJCacheOperationSource.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected KeyGenerator determineKeyGenerator(
		@Nullable CacheDefaults defaults, Class<? extends CacheKeyGenerator> candidate) {

	if (candidate != CacheKeyGenerator.class) {
		return new KeyGeneratorAdapter(this, getBean(candidate));
	}
	else if (defaults != null && CacheKeyGenerator.class != defaults.cacheKeyGenerator()) {
		return new KeyGeneratorAdapter(this, getBean(defaults.cacheKeyGenerator()));
	}
	else {
		return getDefaultKeyGenerator();
	}
}
 
Example #18
Source File: AnnotationJCacheOperationSource.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
protected CachePutOperation createCachePutOperation(Method method, CacheDefaults defaults, CachePut ann) {
	String cacheName = determineCacheName(method, defaults, ann.cacheName());
	CacheResolverFactory cacheResolverFactory =
			determineCacheResolverFactory(defaults, ann.cacheResolverFactory());
	KeyGenerator keyGenerator = determineKeyGenerator(defaults, ann.cacheKeyGenerator());

	CacheMethodDetails<CachePut> methodDetails = createMethodDetails(method, ann, cacheName);
	CacheResolver cacheResolver = getCacheResolver(cacheResolverFactory, methodDetails);
	return new CachePutOperation(methodDetails, cacheResolver, keyGenerator);
}
 
Example #19
Source File: RedisConfig.java    From light-reading-cloud with MIT License 5 votes vote down vote up
/** 配置Key的生成方式 */
@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object o, Method method, Object... objects) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(o.getClass().getName()).append(method.getName());
            for (Object object : objects) {
                stringBuilder.append(object.toString());
            }
            return stringBuilder.toString();
        }
    };
}
 
Example #20
Source File: RedisConfig.java    From light-reading-cloud with MIT License 5 votes vote down vote up
/** 配置Key的生成方式 */
@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object o, Method method, Object... objects) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(o.getClass().getName()).append(method.getName());
            for (Object object : objects) {
                stringBuilder.append(object.toString());
            }
            return stringBuilder.toString();
        }
    };
}
 
Example #21
Source File: JCacheJavaConfigTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void fullCachingConfig() throws Exception {
	AnnotationConfigApplicationContext context =
			new AnnotationConfigApplicationContext(FullCachingConfig.class);

	DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class);
	assertSame(context.getBean(KeyGenerator.class), cos.getKeyGenerator());
	assertSame(context.getBean("cacheResolver", CacheResolver.class),
			cos.getCacheResolver());
	assertSame(context.getBean("exceptionCacheResolver", CacheResolver.class),
			cos.getExceptionCacheResolver());
	JCacheInterceptor interceptor = context.getBean(JCacheInterceptor.class);
	assertSame(context.getBean("errorHandler", CacheErrorHandler.class), interceptor.getErrorHandler());
}
 
Example #22
Source File: RedisCacheConfig.java    From watchdog-framework with MIT License 5 votes vote down vote up
@Bean
@Override
public KeyGenerator keyGenerator(){
    return (target, method, params) -> {
        StringBuilder sb = new StringBuilder();
        sb.append(target.getClass().getName());
        sb.append(method.getName());
        for (Object obj : params) {
            sb.append(obj.toString());
        }
        return sb.toString();
    };

}
 
Example #23
Source File: RedisCacheConfig.java    From spring-boot-plus with Apache License 2.0 5 votes vote down vote up
@Bean
@Override
public KeyGenerator keyGenerator() {
    return (target, method, params) -> {
        StringBuffer redisKey = new StringBuffer();
        redisKey.append(target.getClass().getName()).append("-");
        redisKey.append(method.getName());
        if (params.length > 0) {
            redisKey.append("-").append(Arrays.deepToString(params));
        }
        return redisKey.toString();
    };
}
 
Example #24
Source File: AnnotationJCacheOperationSource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected KeyGenerator determineKeyGenerator(CacheDefaults defaults, Class<? extends CacheKeyGenerator> candidate) {
	if (CacheKeyGenerator.class != candidate) {
		return new KeyGeneratorAdapter(this, getBean(candidate));
	}
	else if (defaults != null && CacheKeyGenerator.class != defaults.cacheKeyGenerator()) {
		return new KeyGeneratorAdapter(this, getBean(defaults.cacheKeyGenerator()));
	}
	else {
		return getDefaultKeyGenerator();
	}
}
 
Example #25
Source File: MyCacheConfig.java    From code with Apache License 2.0 5 votes vote down vote up
@Bean("myKeyGenerator")
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {

        @Override
        public Object generate(Object target, Method method, Object... params) {
            return method.getName() + "[" + Arrays.asList(params).toString() + "]";
        }
    };
}
 
Example #26
Source File: RedisConfig.java    From JavaQuarkBBS with Apache License 2.0 5 votes vote down vote up
@Bean
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        }
    };
}
 
Example #27
Source File: RedisConfig.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 自定义生成key的策略
 *
 * @return
 */
@Bean
@Override
public KeyGenerator keyGenerator() {
    return new KeyGenerator() {
        @Override
        public Object generate(Object target, Method method, Object... params) {
            return target.getClass().getSimpleName() + "_"
                    + method.getName() + "_"
                    + StringUtils.arrayToDelimitedString(params, "_");
        }
    };
}
 
Example #28
Source File: JCacheJavaConfigTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void fullCachingConfig() throws Exception {
	AnnotationConfigApplicationContext context =
			new AnnotationConfigApplicationContext(FullCachingConfig.class);

	DefaultJCacheOperationSource cos = context.getBean(DefaultJCacheOperationSource.class);
	assertSame(context.getBean(KeyGenerator.class), cos.getKeyGenerator());
	assertSame(context.getBean("cacheResolver", CacheResolver.class),
			cos.getCacheResolver());
	assertSame(context.getBean("exceptionCacheResolver", CacheResolver.class),
			cos.getExceptionCacheResolver());
	JCacheInterceptor interceptor = context.getBean(JCacheInterceptor.class);
	assertSame(context.getBean("errorHandler", CacheErrorHandler.class), interceptor.getErrorHandler());
}
 
Example #29
Source File: RedisAutoConfigure.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
@Bean
public KeyGenerator keyGenerator() {
    return (target, method, objects) -> {
        StringBuilder sb = new StringBuilder();
        sb.append(target.getClass().getName());
        sb.append(":" + method.getName() + ":");
        for (Object obj : objects) {
            sb.append(obj.toString());
        }
        return sb.toString();
    };
}
 
Example #30
Source File: RedisCacheConfig.java    From iot-dc3 with Apache License 2.0 5 votes vote down vote up
/**
 * 自定义缓存 Key 生成策略
 *
 * @return KeyGenerator
 */
@Bean
public KeyGenerator commonKeyGenerator() {
    return (target, method, params) -> {
        StringBuilder sb = new StringBuilder();
        sb.append(target.getClass().getName());
        sb.append(".");
        sb.append(method.getName());
        sb.append("#");
        for (Object obj : params) {
            sb.append(obj.toString());
        }
        return sb.toString();
    };
}