如何在Java Spring Boot中实现RedisCache.class来存储键值对


@RestController
@RequestMapping()
public class AuthController extends BaseController {
JwtProvider tokenProvider;
RedisCache<String,UserModel> redisCache;

@Autowired
public AuthController(
JwtProvider tokenProvider,
MessageHelper messageHelper,
ModelMapper modelMapper,
RedisCache<String,UserPrincipalTransformerModel> redisCache
) {
super(AuthController.class, messageHelper, modelMapper);
this.userService = userService;
this.tokenProvider = tokenProvider;
this.loginTokenService = loginTokenService;
this.companyUserService = companyUserService;
this.apiKeyService = apiKeyService;
this.redisCache = redisCache;
}

我想像这样存储键值,rediCache.put("字符串",userModel(;

有人知道如何使用RedisCache.Class并实例化它吗?因为目前我收到了一个错误。

需要一个类型为"io.leract.core.support.caching.RedisCache"的bean,但找不到该bean。

行动:

请考虑在您的配置中定义一个类型为"io.lacetrat.core.support.caching.RedisCache"的bean。。。。。。。。。。。。。。。但我想使用默认的RedisCache.class

/*
* Copyright 2020-2022 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
*
*      https://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 io.lettuce.core.support.caching;
/**
* Interface defining common Redis Cache operations.
*
* @param <K> Key type.
* @param <V> Value type.
* @author Mark Paluch
* @since 6.0
*/
public interface RedisCache<K, V> {
/**
* Retrieve a {@code value} from Redis for the given cache {@code key}.
*
* @param key the key whose associated value is to be returned.
* @return the value to which this Redis cache value maps the specified key (which may be {@code null} itself), or also
*         {@code null} if the Redis cache contains no mapping for this key.
*/
V get(K key);
/**
* Associate the specified value with the specified key in this Redis cache.
*
* @param key the key with which the specified value is to be associated.
* @param value the value to be associated with the specified key.
*/
void put(K key, V value);
/**
* Register a invalidation {@code listener} that is notified if a key in this Redis cache expires or gets modified.
*
* @param listener the listener to notify.
*/
void addInvalidationListener(java.util.function.Consumer<? super K> listener);
/**
* Closes this Redis cache and releases any connections associated with it. If the cache is already closed then invoking
* this method has no effect.
*/
void close();
}

添加redis依赖项

和往常一样,Spring引导在复杂的启动器依赖关系的帮助下使事情变得更容易。您所要做的就是添加Redis启动器。

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

为Redis配置添加适当的设置。如果您在本地使用Redis,则可以跳过以下步骤。

spring.redis.host=localhost
spring.redis.port=8080

在生产中,您可能需要根据服务器添加spring.redis.username和spring.redis.password。

启用缓存

要在Spring引导中启用缓存支持,首先需要使用@EnableCaching对主类进行注释。

@EnableCaching
@SpringBootApplication
public class SpringBootRedisCacheExampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRedisCacheExampleApplication.class, args);
}
}

添加@可缓存注释

找到一个长时间运行的方法,并用@Cacheable对其进行注释。此注释采用的值是缓存名称。密钥是一个唯一的对象,用于以后在缓存中查找值。


@Cacheable(value = "items", key = "#id")
public Item getItem(Integer id) {
Item item = itemRepository.findById(id).orElseThrow(RuntimeException::new);
logger.info("Loading data from DB {}", item);
return item;
}

在这种情况下,我们使用Spring表达式语言(SpEL(将参数值作为键传递。

添加@CacheEvict注释缓存后,值将无限期地保留在那里。因此,缓存抽象永远不会从数据库中提取更新的值。因此,您应该在更新时使用@CacheEvict。

@CacheEvict(value = "items", key = "#id")
public Item updateItem(Integer id, Item request) {
Item item = getItem(id);
item.setPrice(request.getPrice());
item.setProductName(request.getProductName());
return itemRepository.save(item);
}

一旦我们启动应用程序,第一个请求就会转到数据库。随后的请求从Redis缓存中获取数据。我们知道这一点是因为,

日志显示这些记录来自数据库。

c.s.e.s.cache.service.ItemService:Loading data from DB Item{id=2,productName='Pants Large',price=21.99}

将其用作RedisConfiguration,对于JedisCluster Mode=enabled,您也可以将其替换为RedisStandalone用于单实例

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.DefaultJedisClientConfig;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import sg.customs.ntp.rsrf.commonservice.util.JedisUtil;
import javax.annotation.PostConstruct;
@Slf4j
@Configuration
public class RedisConfiguration {
@Value("${spring.data.redis.host:#{''}}")
private String host;
@Value("${spring.data.redis.port:#{6379}}")
private int port;
@Value("${spring.redis.jedis.pool.max-active-connections:#{8}}")
private int maxActive;
@Value("${spring.redis.jedis.pool.max-idle:#{4}}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.min-idle:#{1}}")
private int minIdle;
@Value("${spring.redis.cluster.max-attempts:#{10}}")
private int maxAttempts;
@PostConstruct
public void getJedisClusterConfiguration() {
HostAndPort hostAndPort = new HostAndPort(host, port);
DefaultJedisClientConfig jedisClientConfig = DefaultJedisClientConfig.builder()
.ssl(true)
.build();
GenericObjectPoolConfig<Jedis> genericObjectPoolConfig = new GenericObjectPoolConfig<>();
genericObjectPoolConfig.setMaxIdle(maxIdle);
genericObjectPoolConfig.setMaxTotal(maxActive);
genericObjectPoolConfig.setMinIdle(minIdle);
JedisUtil.setInstance(new JedisCluster(hostAndPort, jedisClientConfig, maxAttempts, genericObjectPoolConfig));
}
}

并将其用作JedisUtil

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.params.SetParams;
@Slf4j
@UtilityClass
public class JedisUtil {
private static JedisCluster jedisCluster;
public static void setInstance(JedisCluster cluster) {
jedisCluster = cluster;
}
public void set(String key, String value) {
try {
jedisCluster.set(key, value);
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
}
public void set(String key, String value, long timeToLive) {
try {
jedisCluster.set(key, value, new SetParams().ex(timeToLive));
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
}
public String get(String key) {
try {
return jedisCluster.get(key);
} catch (Exception e) {
return null;
}
}
public void del(String key) {
try {
jedisCluster.del(key);
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
}
}

最新更新