Using the Redis cache in spring boot

Source: Internet
Author: User
Tags redis server

1.maven Lead Package

< Dependency >            < groupId >org.springframework.boot</groupId>            <  Artifactid>spring-boot-starter-data-redis</artifactid>  </dependency>

Note: Springboot version 1.5.2

2. Configure Application.properties

# Redis Database index (default is 0) spring.redis.database=0# Redis server address spring.redis.host=127.0.0.1# 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 means there is 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 connections in the 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

Note: Sever,mybatis and other configuration do not repeat

3. Add annotations for the Startup class:

@SpringBootApplication @mapperscan ("Com.tqh.demo.mapper") @EnableScheduling @enablecaching  Public class demoapplication {    publicstaticvoid  main (string[] args) {        Springapplication.run (demoapplication. class , args);}    }

4. Create a Redis configuration class

@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. Create a test class User

 Public classUser {String id;    String name;    String age;  PublicString getId () {returnID; }     Public voidsetId (String id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString getage () {returnAge ; }

Note: The database should also create the corresponding table and test data

5. Create Usermapper

@Repository 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}") User FindByID (@Param ("id") String ID); @Update ("Update user set Name=#{name} where Id=#{id}")    voidUpdatabyid (@Param ("id") String ID, @Param ("name") String name); @Delete ("Delete from user where Id=#{id}")    voidDeletebyid (@Param ("id") String ID);}

6. Create UserService, the cache works on this floor

//@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@Service @cacheconfig (cachenames= "Users") Public classuserservice {@Autowired usermapper usermapper; @Cacheable (Key= "#p0")     PublicUser Selectuser (String id) {SYSTEM.OUT.PRINTLN ("Select"); returnUsermapper.findbyid (ID); } @CachePut (Key= "#p0")     Public voidUpdatabyid (string ID, string name) {System.out.println ("Update");    Usermapper.updatabyid (Id,name); }    //If true, all caches are emptied immediately after the method call@CacheEvict (key = "#p0", allentries=true)     Public voidDeletebyid (String id) {SYSTEM.OUT.PRINTLN ("Delete");    Usermapper.deletebyid (ID); }}

7.Controller

@Controller @requestmapping ("/") Public classRediscontroller {@Autowired userservice userservice; @RequestMapping ("Select/{id}") @ResponseBody PublicUser fortest (@PathVariable String id) {returnUserservice.selectuser (ID); } @RequestMapping ("/update/{id}") @ResponseBody Publicstring Update (@PathVariable string id) {Userservice.updatabyid (ID,"AAA"); return"Update Success"; } @RequestMapping ("/delete/{id}") @ResponseBody Publicstring Delete (@PathVariable string id) {Userservice.deletebyid (ID); return"Delete Success"; }}

Test:

The first select succeeds and the "select" is printed in the console, indicating that the MySQL database was queried

The second time will not print, because the Redis cache is checked

Update and delete do not repeat, you can see the keys * in the Redis client to modify and delete the corresponding data changes

Note:

The default persistence scheme for Redis is an RDB, which saves a dump file once per xxx minute if the XXX bar data changes, and resumes automatically after a reboot.

Another scenario is aof, which records every change in the data, both of which can be configured in the redis.conf

Using the Redis cache in spring boot

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.