Spring boot uses the Redis cache

Source: Internet
Author: User
Tags propertyaccessor redis server log4j

Thank the Great God for sharing!

Https://www.cnblogs.com/gdpuzxs/p/7222309.html

(1) Pom.xml introduces the jar package as follows:

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

(2) Modify the project start class, add annotation @enablecaching, turn on the cache function, as follows:

Package Springboot;import Org.springframework.boot.springapplication;import Org.springframework.boot.autoconfigure.springbootapplication;import Org.springframework.cache.annotation.enablecaching;import org.springframework.scheduling.annotation.enablescheduling;@ Springbootapplication@enablescheduling@enablecachingpublic class springbootapplication{public    static void main (string[] args) {        Springapplication.run (springbootapplication.class, args);}    }

(3) Configure Redis connection information in Application.properties as follows:

# Redis Database index (default is 0) spring.redis.database=0# Redis server address spring.redis.host=172.31.19.222# Redis Server connection Port spring.redis.port=6379# Redis Server connection password (default is empty) spring.redis.password=# Connection pool Maximum number of connections (using negative values for No limit) spring.redis.pool.max-active=8# connection pool maximum blocking wait time (using negative values means there is no limit) spring.redis.pool.max-wait=-1# The maximum idle connection in the connection pool spring.redis.pool.max-idle=8# the minimum idle connection in the connection pool spring.redis.pool.min-idle=0# connection time-out (in milliseconds) spring.redis.timeout =0

(4) Create a new Redis cache configuration Class Redisconfig, as follows:

Package Springboot.config;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.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;import Com.fasterxml.jackson.annotation.jsonautodetect;import Com.fasterxml.jackson.annotation.propertyaccessor;import com.fasterxml.jackson.databind.objectmapper;/** * Redis Cache Configuration class * @author Szekinwin * */@ Configuration@enablecachingpublic class Redisconfig extends cachingconfigurersupport{@Value ("${spring.redis.host}") Private String host;    @Value ("${spring.redis.port}") private int port;        @Value ("${spring.redis.timeout}") private int timeout; Custom cache key Generation Policy//@Bean/Public Keygenerator Keygenerator () {//return new Keygenerator () {//@Over                ride//public object generate (object target, Java.lang.reflect.Method Method, Object ... params) {// StringBuffer sb = new StringBuffer ();//Sb.append (Target.getclass (). GetName ());//Sb.app                End (Method.getname ());//For (Object obj:params) {//Sb.append (obj.tostring ());// }//return sb.tostring ();//}//};//}//Cache manager @Bean Public Cachemana Ger CacheManager (@SuppressWarnings ("Rawtypes") redistemplate redistemplate) {Rediscachemanager CacheManager = new        Rediscachemanager (redistemplate); Set cache Expiration Time Cachemanager.setdefaultexpiration (10000);    return CacheManager; } @Bean public redistemplate<string, string> redistemplate (Redisconnectionfactory factory) {Stringredis        Template template = new stringredistemplate (factory);        Setserializer (template);//Set Serialization tool Template.afterpropertiesset ();    return template;            } private void Setserializer (stringredistemplate template) {@SuppressWarnings ({"Rawtypes", "Unchecked"})            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); }}

(5) New Usermapper, as follows:

Package Springboot.dao;import Org.apache.ibatis.annotations.delete;import Org.apache.ibatis.annotations.Insert; Import Org.apache.ibatis.annotations.mapper;import Org.apache.ibatis.annotations.param;import Org.apache.ibatis.annotations.select;import Org.apache.ibatis.annotations.update;import Org.springframework.cache.annotation.cacheconfig;import Org.springframework.cache.annotation.cacheevict;import Org.springframework.cache.annotation.cacheput;import Org.springframework.cache.annotation.cacheable;import Springboot.domain.User; @Mapper @cacheconfig (cachenames = "users") public interface Usermapper {@Insert ("Insert to use        R (Name,age) VALUES (#{name},#{age}) ") int AddUser (@Param (" name ") string name, @Param (" Age ") of string age);        @Select ("SELECT * from user where ID =#{id}") @Cacheable (key = "#p0") User FindByID (@Param ("id") String ID); @CachePut (key = "#p0") @Update ("Update user set Name=#{name} where Id=#{id}") void Updatabyid (@Param ("id") String ID , @Param ("name") String name); If true, all cache @CacheEvict are emptied immediately after the method call (key = "#p0", Allentries=true) @Delete ("Delete from user where Id=#{id}") v    OID Deletebyid (@Param ("id") String ID); }

@Cacheable cache the query results into Redis, (key= "#p0") specifies the first parameter passed in as the Redis key.

@CachePut, specify key to synchronize the updated results to Redis

@CacheEvict, specify key, delete cached data, allentries=true, and purge cache immediately after method call

(6) Service layer and controller layer to follow the previous integration, starting Redis server, Redis Server installation and startup can refer to the previous blog, the address is as follows:

Http://www.cnblogs.com/gdpuzxs/p/6623171.html

(7) Configure the log4j log information as follows:

# # LOG4J Configuration log4j.rootcategory=debug,stdout## Console output log4j.appender.stdout= org.apache.log4j.consoleappenderlog4j.appender.stdout.layout= Org.apache.log4j.patternlayoutlog4j.appender.stdout.layout.conversionpattern=%d{yyyy-mm-dd HH:mm:ss,SSS}%5p%c{1 }:%l-%m%n

(8) Verifying the Redis cache

First, we always insert a data into the user table, and the database is shown as follows:

  

Now, let's look at the id=24 data in the user table and view the information from the console output as follows:

  

Output information from the console we can tell that this time the database query was executed and the Redis cache query results were turned on. Next we look at the id=24 data in the user table again and observe the console as follows:

  

Output information from the console we can tell that this time, instead of executing a database query, we are querying from the Redis cache and returning the results of the query. We look at the information in Redis as follows:

  

The Finduser method uses the annotation @cacheable (key= "#p0") to use the ID as the key value in Redis. When we update the data, we should use @cacheput (key= "#p0") to update the cached data, otherwise the dirty data will be queried.

Spring boot uses the Redis cache

Related Article

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.