Home >Database >Redis >How to apply Redis stand-alone cache of SpringBoot caching mechanism

How to apply Redis stand-alone cache of SpringBoot caching mechanism

WBOY
WBOYforward
2023-06-03 12:41:50930browse

Redis stand-alone cache

Same as Ehcache, if Redis exists under the classpath and Redis has been configured, RedisCacheManager will be used as the cache provider by default. The steps for using Redis stand-alone cache are as follows:

1. Create a project and add cache dependencies

Create a Spring Boot project and add spring-boot-starter-cache and Redis dependencies

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
    </exclusion>
  </exclusions>
</dependency>
<dependency>
  <groupId>io.lettuce</groupId>
  <artifactId>lettuce-core</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-test</artifactId>
  <scope>test</scope>
</dependency>

2. Cache configuration

Redis stand-alone cache only requires developers to perform Redis configuration and cache configuration in application.properties. The code is as follows

# Cache configuration
# Configure the cache name. Each key in Redis has a Prefix, the default prefix is ​​"cache name::"
spring.cache.cache-names=c1,c2
# Configure the cache validity period, that is, the key expiration time in Redis
spring.cache.redis.time -to-live=1800s
# Redis configuration
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password =123456
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.max-wait=- 1ms
spring.redis.jedis.pool.min-idle=0

3. Turn on cache

Enable cache in the project entry class, as follows

@SpringBootApplication
@EnableCaching
public class CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}

Steps 4 and 5 are the same as the Ehcache 2.x application of SpringBoot's brief analysis of the caching mechanism, so no further explanation will be given here

4. Create BookDao

Book

public class Book implements Serializable {
    private Integer id;
    private String name;
    private String author;
    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name=&#39;" + name + &#39;\&#39;&#39; +
                ", author=&#39;" + author + &#39;\&#39;&#39; +
                &#39;}&#39;;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
}

BookDao

@Repository
@CacheConfig(cacheNames = "book_cache")
public class BookDao {
    @Cacheable
    public Book getBookById(Integer id) {
        System.out.println("getBookById");
        Book book = new Book();
        book.setId(id);
        book.setName("三国演义");
        book.setAuthor("罗贯中");
        return book;
    }
    @CachePut(key = "#book.id")
    public Book updateBookById(Book book) {
        System.out.println("updateBookById");
        book.setName("三国演义2");
        return book;
    }
    @CacheEvict(key = "#id")
    public void deleteBookById(Integer id) {
        System.out.println("deleteBookById");
    }
}

5. Create a test class

Create a test class and test the method in Service

@RunWith(SpringRunner.class)
@SpringBootTest
public class CacheApplicationTests {
    @Autowired
    BookDao bookDao;
    @Test
    public void contextLoads() {
        bookDao.deleteBookById(1);
        bookDao.getBookById(1);
        bookDao.getBookById(1);
        bookDao.deleteBookById(1);
        Book b3 = bookDao.getBookById(1);
        System.out.println("b3:"+b3);
        Book b = new Book();
        b.setName("三国演义");
        b.setAuthor("罗贯中");
        b.setId(1);
        bookDao.updateBookById(b);
        Book b4 = bookDao.getBookById(1);
        System.out.println("b4:"+b4);
    }
}

Execute the method, the console prints the log as follows :

deleteBookById
getBookById
deleteBookById
getBookById
b3:Book{id=1, name='Romance of the Three Kingdoms', author='Luo Guanzhong'}
updateBookById
b4:Book{id=1, name='Romance of the Three Kingdoms 2', author='Luo Guanzhong'}

In order to avoid the impact of caching on back-and-forth testing, we first perform a delete operation ( This will also delete the cache). Then a query was executed, printing normally, then another query was executed without printing (the cache was read directly), then deletion was executed, then the query was executed and printing was normal (the deletion operation also deleted the cache), and then the update operation was executed ( The cache is updated at the same time), and finally the query is performed again and the updated data is printed.

The above is the detailed content of How to apply Redis stand-alone cache of SpringBoot caching mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete