Springboot using the Redis cache

Source: Internet
Author: User
Tags propertyaccessor redis server stringbuffer log4j

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

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

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

# Redis Database index (default = 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 (with negative values for No limit) Spring.redis.pool.max- Wait=-1# Maximum idle connection in connection pool Spring.redis.pool.max-idle=8# Minimum idle connection in connection pool spring.redis.pool.min-idle=0# Connection time-out (ms) Spring.redis.timeout=0

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

 PackageSpringboot.config;ImportOrg.springframework.beans.factory.annotation.Value;ImportOrg.springframework.cache.CacheManager;ImportOrg.springframework.cache.annotation.CachingConfigurerSupport;Importorg.springframework.cache.annotation.EnableCaching;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.Jackson2JsonRedisSerializer;ImportCom.fasterxml.jackson.annotation.JsonAutoDetect;ImportCom.fasterxml.jackson.annotation.PropertyAccessor;ImportCom.fasterxml.jackson.databind.ObjectMapper;/*** Redis Cache configuration class *@authorSzekinwin **/@Configuration @enablecaching Public classRedisconfigextendscachingconfigurersupport{@Value ("${spring.redis.host}")    PrivateString host; @Value ("${spring.redis.port}")    Private intPort; @Value ("${spring.redis.timeout}")    Private inttimeout; //Custom Cache key generation policy//@Bean//Public Keygenerator Keygenerator () {//return new Keygenerator () {//@Override//Public object Generate (object target, Java.lang.reflect.Method Method, Object ... params) {//stringbuffer sb = new StringBuffer ();//Sb.append (Target.getclass (). GetName ());//Sb.append (Method.getname ());//For (Object obj:params) {//Sb.append (obj.tostring ());//                }//return sb.tostring ();//            }//        };//    }    //Cache Manager@Bean PublicCacheManager CacheManager (@SuppressWarnings ("Rawtypes") Redistemplate redistemplate) {Rediscachemanager CacheManager=NewRediscachemanager (redistemplate); //Set cache Expiration TimeCachemanager.setdefaultexpiration (10000); returnCacheManager; } @Bean PublicRedistemplate<string, string>redistemplate (Redisconnectionfactory Factory) {stringredistemplate template=Newstringredistemplate (Factory); Setserializer (template);//setting up the serialization toolTemplate.afterpropertiesset (); returntemplate; }     Private voidSetserializer (stringredistemplate template) {@SuppressWarnings ({"Rawtypes", "unchecked"}) Jackson2jsonredisserializer Jackson2jsonredisserializer=NewJackson2jsonredisserializer (Object.class); Objectmapper om=NewObjectmapper ();            Om.setvisibility (Propertyaccessor.all, JsonAutoDetect.Visibility.ANY);            Om.enabledefaulttyping (ObjectMapper.DefaultTyping.NON_FINAL);            Jackson2jsonredisserializer.setobjectmapper (OM);     Template.setvalueserializer (Jackson2jsonredisserializer); }}

 (4) New Usermapper, as follows:

 PackageSpringboot.dao;ImportOrg.apache.ibatis.annotations.Delete;ImportOrg.apache.ibatis.annotations.Insert;ImportOrg.apache.ibatis.annotations.Mapper;ImportOrg.apache.ibatis.annotations.Param;ImportOrg.apache.ibatis.annotations.Select;Importorg.apache.ibatis.annotations.Update;ImportOrg.springframework.cache.annotation.CacheConfig;Importorg.springframework.cache.annotation.CacheEvict;ImportOrg.springframework.cache.annotation.CachePut;Importorg.springframework.cache.annotation.Cacheable;ImportSpringboot.domain.User, @Mapper @cacheconfig (Cachenames= "Users") Public Interfaceusermapper {@Insert ("INSERT into User (Name,age) VALUES (#{name},#{age})")    intAddUser (@Param ("name") String name, @Param ("Age") 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}")    voidUpdatabyid (@Param ("id") String ID, @Param ("name") String name); //If true, all caches are emptied immediately after the method call@CacheEvict (key = "#p0", allentries=true) @Delete ("Delete from user where Id=#{id}")    voidDeletebyid (@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

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

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

  

Springboot using 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.