Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Spring-boot-2.0.3 's redis cache implementation is not what you think.

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

Preface

Happy moment

Xiaobai asked Xiaoming, "there is a pit 5 meters deep in front of you. There is no water in it. How do you get out after you jump in?" Xiao Ming: "come out lying down, how else can you get out?" Xiaobai: "Why come out lying down?" Xiaoming: "5 meters deep pit, there is no water, jump down not to die is very lucky, disabled is sure to be disabled, do not lie out, how can come out?" Xiaobai: "suppose you are not dead or disabled?" Xiao Ming: "you think I'm Superman? that's easy. If you let the water out of your head, you can float it out." Xiaobai: "do you have so much water in your head?" Xiao Ming: "I don't have so much water in my head. Why should I jump?"

My way ahead is long; I see no ending; yet high and low I'll search with my will unbending!

There are still a lot of changes in springboot 1.x to 2.x, and there are slight differences between 2.x. This article will not talk about these differences (I do not know the specific differences, Khan.), I will only talk about the difference between 1.5.9 and 2.0.3 redis cache configuration.

Back to the top.

Springboot1.5.9 cache configuration

Engineering realization

1.x series configurations should all be similar. Let's take a look at the caching implementation of springboot integrating redis in 1.5.9.

Pom.xml

4.0.0

Com.leespring-boot159.cache1.0-SNAPSHOT 1.8 org.springframework.boot spring-boot-starter-parent 1.5.9.RELEASE org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-data-redis

Application.yml

Server:

Port: 8888

Spring:

# redis configuration

Redis:

Database: 0

Host: 127.0.0.1

Port: 6379

Password:

Connection timeout (milliseconds)

Timeout: 2000

Pool:

Maximum number of connections in the connection pool (use negative values to indicate no limit)

Max-active: 8

Maximum blocking wait time for connection pools (use negative values to indicate no limit)

Max-wait:-1

Maximum idle connection in the connection pool

Max-idle: 8

Minimum idle connections in the connection pool

Min-idle: 0

Cache:

Type: redis

Cache:

Expire-time: 180

RedisCacheConfig.java

Package com.lee.cache.config

Import com.fasterxml.jackson.annotation.JsonAutoDetect

Import com.fasterxml.jackson.annotation.PropertyAccessor

Import com.fasterxml.jackson.databind.ObjectMapper

Import org.springframework.beans.factory.annotation.Value

Import org.springframework.cache.CacheManager

Import org.springframework.cache.annotation.CachingConfigurerSupport

Import org.springframework.cache.annotation.EnableCaching

Import org.springframework.cache.interceptor.KeyGenerator

Import org.springframework.context.annotation.Bean

Import org.springframework.context.annotation.Configuration

Import org.springframework.data.redis.cache.RedisCacheManager

Import org.springframework.data.redis.connection.RedisConnectionFactory

Import org.springframework.data.redis.core.RedisTemplate

Import org.springframework.data.redis.core.StringRedisTemplate

Import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer

/ * *

You must inherit CachingConfigurerSupport, otherwise the Bean generated in this class will not take effect (the default generated bean is not replaced, just a normal bean). The cache manager and redisTemplate supported by springboot by default are limited and do not meet our needs at all. The following exception will be thrown:

Org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.String*/

@ Configurationbr/ > * /

@ Configuration

Public class RedisCacheConfig extends CachingConfigurerSupport {

@ Value ("${cache.expire-time:180}")

Private int expireTime

/ / configure the key generator to act on all caches managed by the cache manager

/ / if the key attribute is specified in the cache comments (@ Cacheable, @ CacheEvict, etc.), the key generator @ Beanbr/ > @ Bean will be overwritten.

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 ()

}

}

/ / all caches managed by the cache manager need to have corresponding cache space, otherwise an exception is thrown: No cache could be resolved for 'Builder...@Beanbr/ > @ Bean

RedisCacheManager rcm = new RedisCacheManager (redisTemplate)

Rcm.setDefaultExpiration (expireTime); / / sets the expiration time of caches managed by the cache manager (in seconds)

Return rcm

}

@ Bean

Public RedisTemplate redisTemplate (RedisConnectionFactory factory) {

StringRedisTemplate template = new StringRedisTemplate (factory)

Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer (Object.class)

ObjectMapper om = new ObjectMapper ()

Om.setVisibility (PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY)

Om.enableDefaultTyping (ObjectMapper.DefaultTyping.NON_FINAL)

Jackson2JsonRedisSerializer.setObjectMapper (om)

Template.setValueSerializer (jackson2JsonRedisSerializer)

Template.afterPropertiesSet ()

Return template

}

}

CacheServiceImpl.java

Package com.lee.cache.service.impl

Import com.lee.cache.model.User

Import com.lee.cache.service.ICacheService

Import org.springframework.beans.factory.annotation.Autowired

Import org.springframework.cache.annotation.Cacheable

Import org.springframework.data.redis.core.RedisTemplate

Import org.springframework.stereotype.Service

Import org.springframework.util.StringUtils

Import java.util.ArrayList

Import java.util.List

/ * *

If @ CacheConfig (cacheNames = "hello") is not configured, @ Cacheable must be configured with value, which is equivalent to a specified cache space or an exception will be thrown: if No cache could be resolved for 'Builder... is configured with both @ CacheConfig (cacheNames = "hello") and @ Cacheable (value = "123"), @ Cacheable (value =" 123") will take effect.

Of course, @ CacheConfig has some other configuration items, and Cacheable has some other configuration items * /

@ Servicebr/ > * /

@ Service

@ Autowired

Private RedisTemplate redisTemplate

@ Override

@ Cacheable (value = "test") / / Custom KeyGenerator for key

Public String getName () {

System.out.println ("getName, no cache now...")

Return "brucelee"

}

@ Override

@ Cacheable (value = "user", key = "methodName +'_'+ # p0", unless = "# result.size ()

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report