Springboot 1 + 2 cache

Source: Internet
Author: User

Springboot Cache

In order to implement whether to query data in the data or query the data in the cache, the MyBatis corresponding mapper package log is set to debug in Application.yml.

Spring:  DataSource:    username:root    password:rootpassword    url:jdbc:mysql://localhost:3306/ Springboot    driver-class-name:com.mysql.jdbc.driverdebug:truelogging: level  :    com:      Springbootmybatis:         mapper:debug

Then add @EnableCaching start cache on the main class of Springboot.

Then add the cached annotations on the methods in the service class.

@Cacheable (value = "User") public user Selectuserbyid (Integer id) {    =  Usermapper.selectuserbyid (ID);     return user;}
@Cacheable

? The default is to pass in the parameter (ID) as the cached key, and the return value of the method is stored as value in the cache.

Before the method Selectuserbyid (Integer ID) to go to the cache according to the key to query whether the key data, if there is, directly in the cache query data, and then return, no longer execute the Selectuserbyid method, if not found in the cache the K EY data before we go back to the Selectuserbyid method.

@CachePut
@CachePut (value = "User") public user updateUser (user user) {    usermapper.updateuser (user);     return  user;    }

The default is to pass in the parameter (ID) as the cached key, @CachePut executes after the method executes, writes the result returned by the method to the cache,

The query from the cache is still the old cached data, which needs to be @CachePut (value = "User", key = "#result. Id") or @cacheput (value = "User", key = "#user. ID") As long as the key is set As the user's ID, and then the query based on the ID, you can get the modified data from the cache.

@CacheEvict
@CacheEvict (value = "User", key = "#id")

The purge operation is triggered by default after the corresponding method executes successfully, that is, if the method does not trigger a purge operation because it throws an exception and fails to return successfully, you can use beforeinvocation to change the time to delete the cache, and when Beforeinvocation is set to true, the Deletes the specified element in the cache before executing the method, and deletes the cache regardless of whether the method execution has an exception. Deletes the cache for the specified key. Allentries default is False, when true, the specified key is ignored and all cached elements are deleted. A parameter of the default method is used as the cached key when the key is not specified.

@Caching

@Caching annotations Allow us to specify multiple spring cache-related annotations at the same time on a method or class. It has three properties: cacheable, put, and evict, which are used to specify @cacheable, @CachePut, and @cacheevict, respectively.

  @Target ({elementtype.method, elementtype.type}) @Retention ( Retentionpolicy.runtime) @Inherited @documented  public  @interface   Caching {cacheable[] cacheable ()  default   {};    Cacheput[] put ()  default   {}; Cacheevict[] Evict ()  default   {};}  
@Caching (cacheable = @Cacheable ("Users"), evict = {@CacheEvict ("cache2"),          true   public list<user> Selectuser () {        List<User> users = usermapper.selectuser ();         return users;}
using the Redis cache:

Import the corresponding jar: use Fastjson to serialize value

<Dependency>    <groupId>Org.springframework.boot</groupId>    <Artifactid>Spring-boot-starter-data-redis</Artifactid></Dependency><!--Https://mvnrepository.com/artifact/com.alibaba/fastjson -<Dependency>    <groupId>Com.alibaba</groupId>    <Artifactid>Fastjson</Artifactid>    <version>1.2.47</version></Dependency>

To add a configuration in application.yml:

Spring:     Redis:          Host: #redis installed IP, others can not be configured, the default can meet the test needs
configuring Redis in Springboot 1
ImportCom.alibaba.fastjson.JSON;Importcom.alibaba.fastjson.serializer.SerializerFeature;ImportOrg.springframework.cache.CacheManager;ImportOrg.springframework.cache.annotation.CachingConfigurerSupport;Importorg.springframework.cache.annotation.EnableCaching;ImportOrg.springframework.cache.interceptor.KeyGenerator;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.data.redis.cache.RedisCacheManager;Importorg.springframework.data.redis.connection.RedisConnectionFactory;Importorg.springframework.data.redis.core.RedisTemplate;Importorg.springframework.data.redis.core.StringRedisTemplate;ImportOrg.springframework.data.redis.serializer.RedisSerializer;Importorg.springframework.data.redis.serializer.SerializationException;ImportJava.lang.reflect.Method;ImportJava.nio.charset.Charset, @EnableCaching @configuration Public classRedisconfigextendsCachingconfigurersupport {@Bean Publickeygenerator Wiselykeygenerator () {return NewKeygenerator () {@Override Publicobject Generate (Object target, Method method, Object ... params) {StringBuilder sb=NewStringBuilder ();                Sb.append (Target.getclass (). GetName ());                Sb.append (Method.getname ());  for(Object obj:params) {sb.append (obj.tostring ()); }                returnsb.tostring ();    }        }; } @Bean PublicCacheManager CacheManager (@SuppressWarnings ("Rawtypes") Redistemplate redistemplate) {return NewRediscachemanager (redistemplate); } @Bean PublicRedistemplate<string, string>redistemplate (Redisconnectionfactory Factory) {stringredistemplate template=Newstringredistemplate (Factory); Fastjsonredisserializer<Object> serializer =NewFastjsonredisserializer<> (Object.class);        Template.setvalueserializer (serializer);        Template.afterpropertiesset (); returntemplate; }    Private Static classFastjsonredisserializer<t>ImplementsRedisserializer<t> {        Private Static FinalCharset default_charset = Charset.forname ("UTF-8"); PrivateClass<t>Clazz;  PublicFastjsonredisserializer (class<t>clazz) {             This. Clazz =Clazz; } @Override Public byte[] Serialize (T t)throwsSerializationException {if(T = =NULL) {                return New byte[0]; }            returnjson.tojsonstring (t, serializerfeature.writeclassname). GetBytes (Default_charset); } @Override PublicT Deserialize (byte[] bytes)throwsSerializationException {if(bytes = =NULL|| Bytes.length <= 0) {                return NULL; } String str=NewString (bytes, default_charset); return(T) json.parseobject (str, clazz); }    }}

The cached annotations on the test class can then be used to view data that has been serialized in JSON format in Redis.

configuring Redis in Springboot2

Other configurations do not move, need to modify Redisconfig.java because springboot2 in new Rediscachemanager (redistemplate); abandoned.

@Bean PublicCacheManager CacheManager (redisconnectionfactory connectionfactory) {//Initialize a rediscachewriterRediscachewriter Rediscachewriter =Rediscachewriter.nonlockingrediscachewriter (connectionfactory); //the value of Set CacheManager is serialized as Fastjsonredisserializer, but in fact Rediscacheconfiguration uses Stringredisserializer to serialize key by default, ClassLoader loader = This. GetClass (). getClassLoader (); Fastjsonredisserializer Fastjsonredisserializer=NewFastjsonredisserializer<>(Loader.getclass ()); Redisserializationcontext.serializationpair<Object> pair =RedisSerializationContext.SerializationPair.fromSerializer (Fastjsonredisserializer); Rediscacheconfiguration Defaultcacheconfig=rediscacheconfiguration.defaultcacheconfig (). Serializevalueswith (pair); Rediscachemanager CacheManager=NewRediscachemanager (Rediscachewriter, defaultcacheconfig); returnCacheManager; }

This setting can be used normally.

Springboot 1 + 2 cache

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.