{"id":1188,"date":"2025-11-20T18:52:04","date_gmt":"2025-11-20T10:52:04","guid":{"rendered":"http:\/\/www.max-shu.com\/blog\/?p=1188"},"modified":"2025-11-20T18:52:06","modified_gmt":"2025-11-20T10:52:06","slug":"springboot%e4%bd%bf%e7%94%a8redis%e5%81%9a%e7%bc%93%e5%ad%98","status":"publish","type":"post","link":"http:\/\/www.max-shu.com\/blog\/?p=1188","title":{"rendered":"SpringBoot\u4f7f\u7528Redis\u505a\u7f13\u5b58"},"content":{"rendered":"\n<p><strong>\u9996\u5148\u5f15\u5165dependency\uff1a<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;dependency><br>    &lt;groupId>org.springframework.boot&lt;\/groupId><br>    &lt;artifactId>spring-boot-starter-data-redis&lt;\/artifactId><br>&lt;\/dependency><br>&lt;dependency><br>    &lt;groupId>org.apache.commons&lt;\/groupId><br>    &lt;artifactId>commons-pool2&lt;\/artifactId><br>    &lt;version>2.12.0&lt;\/version><br>&lt;\/dependency><br><\/pre>\n\n\n\n<p><\/p>\n\n\n\n<p><strong>\u5176\u6b21\u5728applicaion.yml\u91cc\u9762\u589e\u52a0\u914d\u7f6e\uff1a<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">spring:<br>  cache:<br>    type: <em>redis<br>    <\/em>redis: <em># \u9ad8\u5c42redis\u6ce8\u89e3\u652f\u6301\u914d\u7f6e\u4fe1\u606f<br>        <\/em>enable-statistics: false <em># \u662f\u5426\u5f00\u542f\u7f13\u5b58\u7edf\u8ba1<br>        <\/em>key-prefix: \"${spring.application.name}_${spring.profiles.active}:\" <em># \u4f8b\u5b50\uff1a\"demo_dev:\"\uff0c\u4e3aRedis\u7684KEY\u62fc\u63a5\u524d\u7f00<br>        <\/em>use-key-prefix: true <em># \u662f\u5426\u62fc\u63a5KEY\u524d\u7f00<br>        <\/em>time-to-live: 3600000 <em># 1\u5c0f\u65f6\uff0c\u7f13\u5b58\u8fc7\u671f\u65f6\u95f4,\u5355\u4f4dms<br>        <\/em>cache-null-values: false <em># \u662f\u5426\u5141\u8bb8\u7f13\u5b58\u7a7a\u6570\u636e\uff0c\u5f53\u67e5\u8be2\u5230\u7684\u7ed3\u679c\u4e3a\u7a7a\u65f6\u7f13\u5b58\u7a7a\u6570\u636e\u5230redis\u4e2d<br><\/em>  data:<br>    redis: <em># \u5e95\u5c42redis\u8fde\u63a5\u4fe1\u606f<br>        <\/em>host: 127.0.0.1<br>        port: 6379<br>        password: passwordtest<br>        database: 0 <em># \u903b\u8f91\u6570\u636e\u5e93\u540d\u5b57\uff0c0\u523015<br>        <\/em>timeout: 5000 <em># \u8fde\u63a5\u8d85\u65f6\uff0c\u6beb\u79d2<br>        <\/em>client-type: <em>lettuce # lettuce\u8fde\u63a5\u6c60\u6216\u8005jedis\u8fde\u63a5\u6c60<br>        <\/em>lettuce:<br>            pool:<br>                max-active: 50<br>                max-idle: 10<br>\u540c\u65f6\u53ef\u4ee5\u9009\u62e9\u6253\u5f00log\uff1a<br>logging:<br>    level:<br>        org:<br>                cache: debug<br>                data:<br>                    redis: debug<br>        io:<br>            lettuce:<br>                core: debug<br><\/pre>\n\n\n\n<p><strong>\u7136\u540e\u5728application\u4e3b\u7c7b\u589e\u52a0\u6ce8\u89e3\uff1a<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">@EnableScheduling<br>@EnableCaching  <em>\/\/ \u542f\u7528 Spring Cache<br><\/em>@SpringBootApplication<br>public class DemoApplication {<br>    public static void main(String[] args) {<br>        SpringApplication.<em>run<\/em>(DemoApplication.class, args);<br>    }<br>}<br><br><strong>\u518d\u5b9e\u73b0\u4e00\u4e2a\u914d\u7f6e\u7c7b\uff1a<\/strong><br>@Configuration<br>@AutoConfigureBefore(RedisAutoConfiguration.class) \/\/\u9632\u6b62\u51b2\u7a81\uff0c\u4f18\u5148\u4f7f\u7528\u8fd9\u91cc\u5b9a\u4e49\u7684<br>public class MyRedisConofig extends CachingConfigurerSupport {<br>    private final Logger log = LoggerFactory.getLogger(MyRedisConofig.class);<br><br>    @Value(\"${spring.cache.redis.time-to-live}\")<br>    private Integer ttl;<br>    @Value(\"${spring.cache.redis.key-prefix}\")<br>    private String keyPrefix;<br>    @Value(\"${spring.cache.redis.use-key-prefix}\")<br>    private Boolean useKeyPrefix;<br>    @Value(\"${spring.cache.redis.cache-null-values}\")<br>    private Boolean cacheNullValues;<br><br>    @Value(\"${spring.data.redis.host}\")<br>    private String host;<br>    @Value(\"${spring.data.redis.port}\")<br>    private Integer port;<br>    @Value(\"${spring.data.redis.password}\")<br>    private String password;<br>    @Value(\"${spring.data.redis.database}\")<br>    private Integer database;<br>    @Value(\"${spring.data.redis.timeout}\")<br>    private Integer timeout;<br>    @Value(\"${spring.data.redis.lettuce.pool.max-active}\")<br>    private Integer maxActive;<br>    @Value(\"${spring.data.redis.lettuce.pool.max-idle}\")<br>    private Integer maxIdle;<br><br>    @Bean<br>    public RedisCacheManager cacheManager() {<br>        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration.defaultCacheConfig()<br>            .entryTtl(Duration.ofMillis(ttl)) \/\/ \u9ed8\u8ba4\u6ca1\u6709\u7279\u6b8a\u6307\u5b9a\u7684ttl\uff0c \u901a\u8fc7 cacheName \u62fc\u63a5\u6307\u5b9a\u7684ttl\u5728 MyRedisCacheManager \u7c7b\u4e2d\u5b9e\u73b0<br>            .computePrefixWith(cacheName -> keyPrefix + cacheName + \":\") \/\/\u9ed8\u8ba4enable\u4e86 usekeyPrefix \u548c cacheNullValues<br>            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(<br>                new GenericJackson2JsonRedisSerializer()));  \/\/\u5e8f\u5217\u5316\u6362\u6210json\u65b9\u5f0f<br>        if(! useKeyPrefix ) {<br>            log.info(\"useKeyPrefix is false.\");<br>            defaultCacheConfig = defaultCacheConfig.computePrefixWith(cacheName -> cacheName + \":\").disableKeyPrefix(); \/\/\u9ed8\u8ba4\u4e3aenbale\u7684<br>        }<br>        if(! cacheNullValues){<br>            log.info(\"cacheNullValues is false.\");<br>            defaultCacheConfig = defaultCacheConfig.disableCachingNullValues(); \/\/\u9ed8\u8ba4\u4e3aenbale\u7684<br>        }<br><br>        MyRedisCacheManager redisCacheManager = new MyRedisCacheManager(<br>            RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory()), defaultCacheConfig);<br>        return redisCacheManager;<br>    }<br><br>    @Bean<br>    public RedisConnectionFactory redisConnectionFactory() {<br>        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();<br>        configuration.setHostName(host);<br>        configuration.setPort(port);<br>        configuration.setPassword(password);<br>        configuration.setDatabase(database);<br><br>        ClientOptions clientOptionsBuilder = ClientOptions.builder()<br>            .socketOptions(SocketOptions.builder().connectTimeout(Duration.ofMillis(timeout)).build())<br>            .autoReconnect(true)<br>            .build();<br><br>        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();<br>        poolConfig.setMaxTotal(maxActive);<br>        poolConfig.setMaxIdle(maxIdle);<br>        LettucePoolingClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder()<br>            .clientOptions(clientOptionsBuilder)<br>            \/\/.clientResources(DefaultClientResources.builder().build())<br>            \/\/.commandTimeout(Duration.ofMillis(timeout))<br>            \/\/.shutdownTimeout(Duration.ofMillis(timeout))<br>            .poolConfig(poolConfig)<br>            .build();<br>        LettuceConnectionFactory factory = new LettuceConnectionFactory(configuration, clientConfiguration);<br>        return factory;<br>    }<br><br>    \/\/\u9632\u6b62\u548cRedisAutoConfiguration\u91cc\u9762\u7684stringRedisTemplate\u51b2\u7a81\uff0c\u4e0d\u5b9a\u4e49\u5b83\u4e86<br>\/\/    @Bean<br>\/\/    public RedisTemplate&lt;String, String> stringRedisTemplate() {<br>\/\/        RedisTemplate&lt;String, String> redisTemplate = new StringRedisTemplate();<br>\/\/        redisTemplate.setConnectionFactory(redisConnectionFactory());<br>\/\/        return redisTemplate;<br>\/\/    }<br><br>}<br><br><strong>\u518d\u5b9e\u73b0\u4e00\u4e2aMyRedisCacheManager\u7684\u7c7b\uff0c\u8fd9\u662f\u4e3a\u4e86\u80fd\u8ba9\u6bcf\u4e2acacheName\u80fd\u591f\u5355\u72ec\u8bbe\u7f6ettl\uff08\u7c7b\u4f3c\uff1a@CacheConfig(cacheNames = \"demoCache#3600\")\u7684#\u53f7\u4e4b\u540e\u7684\u6574\u6570\u503c\u8868\u793attl\u4e3a3600\u79d2\uff09\uff1a<\/strong><br>public class MyRedisCacheManager extends RedisCacheManager {<br>    public MyRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {<br>        super(cacheWriter, defaultCacheConfiguration);<br>    }<br><br>    @Override<br>    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {<br>        \/\/ \u7c7b\u4f3c\u8fd9\u79cd\u5b9a\u4e49 @Cacheable(cacheNames = \"demoCache#3600\") \u6216\u8005 @CacheConfig(cacheNames = \"demoCache#3600\") \uff0c<br>        \/\/ \u8868\u793a\u7f13\u5b58\u7684\u8fc7\u671f\u65f6\u95f4\u662f3600\u79d2\u3002<br>        String[] array = StringUtils.delimitedListToStringArray(name, \"#\");<br>        name = array[0];<br>        if (array.length > 1) { \/\/ \u89e3\u6790TTL<br>            long ttl = Long.parseLong(array[1]);<br>            cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl)); \/\/ \u6ce8\u610f\u5355\u4f4d\u6211\u6b64\u5904\u7528\u7684\u662f\u79d2\uff0c\u800c\u975e\u6beb\u79d2<br>        }<br>        return super.createRedisCache(name, cacheConfig);<br>    }<br>}<br><br><strong>\u6700\u540e\u505a\u4e00\u4e2a\u5728Repo\u7684Redis\u7f13\u5b58\u4e0b\u7684\u4ee3\u7406\u7c7b\uff1a<\/strong><br>@Service<br>@CacheConfig(cacheNames = \"DemoEntity#86400\") \/\/MyRedisCacheManager\u91cc\u9762\u5b9e\u73b0\u7684\"#\"\u540e\u9762\u7684\u6570\u5b57\u662f\u7f13\u5b58\u65f6\u95f4\uff0c\u5355\u4f4d\u79d2<br>public class DemoRepoRedis {<br>    private final Logger log = LoggerFactory.getLogger(getClass());<br><br>    @Autowired<br>    private DemoRepo demoRepo;<br><br>    @CachePut(key=\"#result.id\", unless = \"#result == null\") \/\/\u4fee\u6539\u6216\u65b0\u589e\u540e\u7f13\u5b58\uff0c\u65b9\u4fbffind\u65f6\u76f4\u63a5\u7528id\u67e5\u8be2<br>    public DemoEntity save(DemoEntity entity){<br>        return demoRepo.save(entity);<br>    }<br><br>    @Cacheable(key = \"#id\", unless = \"#result == null\") \/\/null\u503c\u4e0d\u7f13\u5b58<br>    public DemoEntity findById(Long id){<br>        log.info(\"redis not cache, findById: \" + id);<br>        return demoRepo.findById(id);<br>    }<br><br>    @CacheEvict(key = \"#id\") \/\/ \u6e05\u9664\u8be5id\u5bf9\u5e94\u7f13\u5b58<br>    public void deleteOne(Long id){<br>        demoRepo.deleteOne(id);<br>    }<br><br>    @CacheEvict(allEntries = true) \/\/ \u540c\u6b65\u6e05\u9664\u7f13\u5b58<br>    public void deleteAll(){<br>        demoRepo.deleteAll();<br>    }<br>}<br><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u9996\u5148\u5f15\u5165dependency\uff1a &lt;dependency> &lt;groupId>org.springf &hellip;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[63],"tags":[943,941,929,196,877,942],"class_list":["post-1188","post","type-post","status-publish","format-standard","hentry","category-63","tag-cache","tag-cacheput","tag-jpa","tag-redis","tag-springboot","tag-942"],"views":253,"_links":{"self":[{"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1188","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1188"}],"version-history":[{"count":1,"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1188\/revisions"}],"predecessor-version":[{"id":1189,"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=\/wp\/v2\/posts\/1188\/revisions\/1189"}],"wp:attachment":[{"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1188"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1188"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.max-shu.com\/blog\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1188"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}