Spring Boot Redis如何将实体存储键的分隔符从:改为.?
Hey there! I've got you covered on this. When using Spring Data Redis with @RedisHash, the default key separator is a colon, but we can easily switch it to a dot either globally or for a specific entity. Here are two straightforward approaches:
1. Global Configuration (All Entities)
If you want every entity annotated with @RedisHash to use a dot as the separator, just add this line to your configuration file:
For application.properties
spring.data.redis.keyspace-separator=.
For application.yml
spring: data: redis: keyspace-separator: "."
That's it! Now all your Redis keys will use a dot instead of a colon. For your Product entity, saving an instance with id 0 will create the key product.0.
2. Entity-Specific Configuration (Only for Product)
If you only want the Product entity to use the dot separator (leaving others with the default colon), create a custom configuration class:
import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.mapping.KeyspaceConfiguration; import org.springframework.data.redis.core.mapping.KeyspaceSettings; import java.util.List; @Configuration public class ProductRedisKeyConfig extends KeyspaceConfiguration { @Override protected Iterable<KeyspaceSettings> initialConfiguration() { // Configure settings specifically for the Product class KeyspaceSettings productKeySettings = new KeyspaceSettings(Product.class, "product"); productKeySettings.setSeparator("."); return List.of(productKeySettings); } }
This configuration tells Spring Data Redis to use a dot as the separator only for the Product entity, while other entities will keep using the colon.
Verify the Result
After applying either of these changes, when you call dao.save(product) with product.setId("0"), you'll find the key product.0 in your Redis database instead of product:0.
内容的提问来源于stack exchange,提问作者tenticon

