我的spring boot项目有以下配置。
@SpringBootApplication
@EnableTransactionManagement
@EnableCaching
@EnableScheduling
@EnableAsync
public class Application {
String redisHost = "localhost";
int redisPort = 6379;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(redisHost);
factory.setPort(redisPort);
factory.setUsePool(true);
return factory;
}
@Bean
RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<Object, Object>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
@Bean
public CacheManager cacheManager() {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
return cacheManager;
}
}
此外,我还关注maven对POM的依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
我有一个单独的redis服务器运行在我的本地机器上的定义端口。另外,在我的服务类中,我有像@cacheable、@cacheput这样的注释来支持缓存。
如果您使用的是Spring Boot,那么您的大部分Redis配置都是不必要的,因为Spring Boot提供了Redis的“自动配置”支持,既可以作为数据源,也可以作为缓存提供程序。
您也没有具体说明使用什么版本的Spring Boot(例如1.5.0.rc1
)来运行应用程序,或者在应用程序的类路径上是否有任何application.properties
,如果您显式指定Spring.cache.type
(例如,设置为“redis”以外的东西),这可能会产生差异。
但是,一般来说,我看不出您的Redis或Spring Cache@configuration
类有什么问题。但是,不显式设置cacheManager.setUsePrefix(true)
似乎确实有问题。当我设置这个rediscacheManager
属性('use prefix')时,所有工作都按预期进行。
我不是(Spring Data)Redis专家,所以我不确定为什么需要这样做。但是,我的测试配置基于Spring Boot对Redis缓存的“自动配置”支持以及您的@configuration
“application”类,如上图所示。
而且,由于您可以消除大部分显式配置,还可以使用Spring Boot对Redis的“自动配置”支持作为数据源,所以我在测试类中添加了一个“AutoRedisconfiguration”
@configuration
类。即。您可以使用它来配置Redis,而不是我的其他@configuration
类(“CustomRedisconfiguration”
),后者使用您的配置+修复程序。
下面是完整的测试示例...
/*
* Copyright 2017 the original author or authors.
*
* 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.spring.cache;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Arrays;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.PostConstruct;
import org.junit.Before;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.MethodSorters;
import org.spring.cache.CachingWithRedisIntegrationTest.CachingWithRedisConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
/**
* Integration tests testing Spring's Cache Abstraction using Spring Data Redis auto-configured with Spring Boot.
*
* To run this test, first start a Redis Server on localhost listening on the default port, 6379.
*
* @author John Blum
* @see org.junit.Test
* @since 1.0.0
*/
@RunWith(SpringRunner.class)
@ActiveProfiles("auto")
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@ContextConfiguration(classes = CachingWithRedisConfiguration.class)
@SuppressWarnings("unused")
public class CachingWithRedisIntegrationTest {
protected static final int REDIS_PORT = 6379;
protected static final String REDIS_HOST = "localhost";
private AtomicBoolean setup = new AtomicBoolean(false);
@Autowired
private MathService mathService;
@Autowired(required = false)
private RedisTemplate<Object, Object> redisTemplate;
@Before
public void setup() {
if (redisTemplate != null && !setup.getAndSet(true)) {
redisTemplate.delete(Arrays.asList(0L, 1L, 2L, 4L, 8L));
}
}
@Test
public void firstCacheMisses() {
assertThat(mathService.factorial(0L)).isEqualTo(1L);
assertThat(mathService.wasCacheMiss()).isTrue();
assertThat(mathService.factorial(1L)).isEqualTo(1L);
assertThat(mathService.wasCacheMiss()).isTrue();
assertThat(mathService.factorial(2L)).isEqualTo(2L);
assertThat(mathService.wasCacheMiss()).isTrue();
assertThat(mathService.factorial(4L)).isEqualTo(24L);
assertThat(mathService.wasCacheMiss()).isTrue();
assertThat(mathService.factorial(8L)).isEqualTo(40320L);
assertThat(mathService.wasCacheMiss()).isTrue();
}
@Test
public void thenCacheHits() {
assertThat(mathService.factorial(0L)).isEqualTo(1L);
assertThat(mathService.wasCacheMiss()).isFalse();
assertThat(mathService.factorial(1L)).isEqualTo(1L);
assertThat(mathService.wasCacheMiss()).isFalse();
assertThat(mathService.factorial(2L)).isEqualTo(2L);
assertThat(mathService.wasCacheMiss()).isFalse();
assertThat(mathService.factorial(4L)).isEqualTo(24L);
assertThat(mathService.wasCacheMiss()).isFalse();
assertThat(mathService.factorial(8L)).isEqualTo(40320L);
assertThat(mathService.wasCacheMiss()).isFalse();
}
interface MathService {
boolean wasCacheMiss();
long factorial(long number);
}
@EnableCaching
@SpringBootConfiguration
@Import({ AutoRedisConfiguration.class, CustomRedisConfiguration.class })
static class CachingWithRedisConfiguration {
@Bean
MathService mathService() {
return new MathService() {
private final AtomicBoolean cacheMiss = new AtomicBoolean(false);
@Override
public boolean wasCacheMiss() {
return cacheMiss.getAndSet(false);
}
@Override
@Cacheable(cacheNames = "Factorials")
public long factorial(long number) {
cacheMiss.set(true);
Assert.isTrue(number >= 0L, String.format("Number [%d] must be greater than equal to 0", number));
if (number <= 2L) {
return (number < 2L ? 1L : 2L);
}
long result = number;
while (--number > 1) {
result *= number;
}
return result;
}
};
}
@Bean
@Profile("none")
CacheManager cacheManager() {
return new ConcurrentMapCacheManager();
}
}
@Profile("auto")
@EnableAutoConfiguration
@SpringBootConfiguration
static class AutoRedisConfiguration {
@PostConstruct
public void afterPropertiesSet() {
System.out.println("AUTO");
}
@Bean
static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer =
new PropertySourcesPlaceholderConfigurer();
propertySourcesPlaceholderConfigurer.setProperties(redisProperties());
return propertySourcesPlaceholderConfigurer;
}
static Properties redisProperties() {
Properties redisProperties = new Properties();
redisProperties.setProperty("spring.cache.type", "redis");
redisProperties.setProperty("spring.redis.host", REDIS_HOST);
redisProperties.setProperty("spring.redis.port", String.valueOf(REDIS_PORT));
return redisProperties;
}
}
@Profile("custom")
@SpringBootConfiguration
static class CustomRedisConfiguration {
@PostConstruct
public void afterPropertiesSet() {
System.out.println("CUSTOM");
}
@Bean
JedisConnectionFactory jedisConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(REDIS_HOST);
factory.setPort(REDIS_PORT);
factory.setUsePool(true);
return factory;
}
@Bean
RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
@Bean
CacheManager cacheManager() {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate());
cacheManager.setUsePrefix(true); // THIS IS NEEDED!
return cacheManager;
}
}
}
希望这有帮助!
干杯,约翰
本文向大家介绍SpringBoot使用Redis缓存的实现方法,包括了SpringBoot使用Redis缓存的实现方法的使用技巧和注意事项,需要的朋友参考一下 (1)pom.xml引入jar包,如下: (2)修改项目启动类,增加注解@EnableCaching,开启缓存功能,如下: (3)application.properties中配置Redis连接信息,如下: (4)新建Redis
本文向大家介绍SpringBoot项目中使用redis缓存的方法步骤,包括了SpringBoot项目中使用redis缓存的方法步骤的使用技巧和注意事项,需要的朋友参考一下 本文介绍了SpringBoot项目中使用redis缓存的方法步骤,分享给大家,具体如下: Spring Data Redis为我们封装了Redis客户端的各种操作,简化使用。 - 当Redis当做数据库或者消息队列来操作时,我们
本文向大家介绍在 WildFly 中启用 Hibernate 缓存,包括了在 WildFly 中启用 Hibernate 缓存的使用技巧和注意事项,需要的朋友参考一下 示例 要在WildFly中为Hibernate启用二级缓存,请将此属性添加到persistence.xml文件中: 您还可以使用以下属性启用查询缓存: 启用Hibernate的二级缓存时,WildFly不需要您定义缓存提供程序,因为
在应用程序(Spring引导服务)启动时,需要清除Redis缓存。 Redis运行在另一个docker容器中,该容器具有自己的卷映射。因为它保留了旧的缓存,所以即使在应用程序重新启动后,应用程序也会从Redis缓存而不是数据库中拾取数据 > 尝试了的,但它从未被调用。 在Application ationMain类中尝试了,但是它没有清除缓存。 尝试使用,但仍然没有运气 @组件公共类应用程序启动{
从我的客户端,我正在从服务器查询一些枚举。现在,我希望在服务器上查询完这些枚举后,立即将其缓存到客户端中。 我尝试设置缓存控制,如下所示: 响应标头似乎已正确设置为缓存控制:最大年龄=3600。我还禁用了安全配置中的所有http头,如下所示: 遗憾的是,响应没有缓存在浏览器中。在查询资源时,查询将再次转到服务器。 同时,我完全删除了Spring Security,但它仍然不起作用。我没有正确理解什
如何启用此处列出的ExecutorServiceMetrics? https://github.com/micrometer-metrics/micrometer/blob/master/micrometer-core/src/main/java/io/micrometer/core/instrument/binder/jvm/ExecutorServiceMetrics.java SpringB