Spring Boot Learning note--spring boot and Redis integration

Source: Internet
Author: User

I. Adding a REDIS cache 1. Adding Redis start-up dependencies

Add spring boot support for Redis dependency configuration in Pom.xml, as follows:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-redis</artifactId>    <version>1.4.7.RELEASE</version></dependency>

Https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-redis/1.4.7.RELEASE

2. Add cache annotations

(1) In the boot class Demoapplication.java, add the @enablecaching annotation to open the cache, add the following code:
Demoapplication.java:

package com.zifeiy.demo;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cache.annotation.EnableCaching;@SpringBootApplication@EnableCachingpublicclass DemoApplication {    publicstaticvoidmain(String[] args) {        SpringApplication.run(DemoApplication.class, args);    }}

(2) Add @cacheable annotations on the GetAllUsers () method of the business logic class Userserviceimpl to support caching, and add the following implementation code:
Userserviceimpl.java:

    // 查询所有用户    @Override    @Cacheable(value="UserCache",key="‘user.getAllUsers‘")    publicgetAllUsers() {        returnthis.UserMapper.getAllUsers();    }

It is important to note that the key attribute in the @Cacheable annotation, in addition to being quoted in English double quotation marks, also needs to be enclosed in English single quotation marks, or the system will make an error when performing a cache operation.
If you forget to add single quotes, you might end up with an error like this:

EL1008E: Property or field ‘user‘ cannot be found on object of type ‘org.springframework.cache.interceptor.CacheExpressionRootObject‘ - maybe not public or not valid?] with root cause
3. Enabling entity classes to implement serializable interfaces

In order to facilitate the transfer of data, the entity class user is required to implement the serialization interface serializable, the code is as follows:

publicclassimplements Serializable {    private Integer id;    private String username;    private String address;    ...
4. Develop a Redis cache host address

Typically, Redis caches and Web applications are not deployed on a single machine, and Redis needs to be called remotely at this point. Add the configuration for the specified Redis host and its port number in Application.properties, as follows:

spring.redis.host=127.0.0.1spring.redis.port=6379
5. Start the project and test the cache usage

Start the Redis service, start the local project, enter the access address in the browser address bar http://localhost:8080/user.html , and the display information in the Eclipse console is as follows:

2018-05-20 11:10:03.486 DEBUG 9369 --- [nio-8080-exec-8] c.z.demo.mapper.UserMapper.getAllUsers   : ==>  Preparing: select * from tb_user 2018-05-20 11:10:03.519 DEBUG 9369 --- [nio-8080-exec-8] c.z.demo.mapper.UserMapper.getAllUsers   : ==> Parameters: 2018-05-20 11:10:03.574 DEBUG 9369 --- [nio-8080-exec-8] c.z.demo.mapper.UserMapper.getAllUsers   : <==      Total: 3

As you can see, the program has executed the SELECT statement and queried 3 data. If you refresh the browser, the query operation will be performed again. Before the Redis cache is used, every time a page is refreshed, the database is queried once, and after the cache is added, it is discovered that only one query statement appears in the console (I do not seem to appear here), which means that the configured Redis cache is already in effect.

Second, delete the Redis cache

Data in Redis does not persist, and when you perform add, update, and delete operations, the data in the database changes, and the data in the Redis cache needs to change accordingly. To ensure that the data in the Redis cache is consistent with the database, you typically need to clear the cache before you perform add, update, and delete operations, and then store the new data in the Redis cache the next time you perform a query operation.
The ability to implement a clear cache is simple, just use the @cacheevict annotation in the appropriate method. To delete the user as an example, add the @cacheevict annotation information on the DeleteUser () method of the user's business logic class as follows:
Userserviceimpl.java:

    // 删除用户    @Override    @CacheEvict(value="UserCache",key="‘user.getAllUsers‘")    publicvoiddeleteUser(Integer id) {        System.out.println("删除了id为 "" 的用户");        this.UserMapper.delete(id);    }

When you start the project, http://localhost:8080/user/delete/1 the id=1 user information is deleted when you enter it.
The Eclipse console information is as follows:

2018-05-20 13:07:45.709 DEBUG 13739 --- [nio-8080-exec-1] c.zifeiy.demo.mapper.UserMapper.delete   : ==>  Preparing: DELETE FROM tb_user WHERE id=? 2018-05-20 13:07:45.761 DEBUG 13739 --- [nio-8080-exec-1] c.zifeiy.demo.mapper.UserMapper.delete   : ==> Parameters: 1(Integer)2018-05-20 13:07:45.773 DEBUG 13739 --- [nio-8080-exec-1] c.zifeiy.demo.mapper.UserMapper.delete   : <==    Updates: 1

The cache in Redis is also deleted accordingly.

Spring Boot Learning note--spring boot and Redis integration

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.