How to apply Redis stand-alone cache of SpringBoot caching mechanism
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='" + name + '\'' + ", author='" + author + '\'' + '}'; } 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!

Redis is an open source memory data structure storage used as a database, cache and message broker, suitable for scenarios where fast response and high concurrency are required. 1.Redis uses memory to store data and provides microsecond read and write speed. 2. It supports a variety of data structures, such as strings, lists, collections, etc. 3. Redis realizes data persistence through RDB and AOF mechanisms. 4. Use single-threaded model and multiplexing technology to handle requests efficiently. 5. Performance optimization strategies include LRU algorithm and cluster mode.

Redis's functions mainly include cache, session management and other functions: 1) The cache function stores data through memory to improve reading speed, and is suitable for high-frequency access scenarios such as e-commerce websites; 2) The session management function shares session data in a distributed system and automatically cleans it through an expiration time mechanism; 3) Other functions such as publish-subscribe mode, distributed locks and counters, suitable for real-time message push and multi-threaded systems and other scenarios.

Redis's core functions include memory storage and persistence mechanisms. 1) Memory storage provides extremely fast read and write speeds, suitable for high-performance applications. 2) Persistence ensures that data is not lost through RDB and AOF, and the choice is based on application needs.

Redis'sServer-SideOperationsofferFunctionsandTriggersforexecutingcomplexoperationsontheserver.1)FunctionsallowcustomoperationsinLua,JavaScript,orRedis'sscriptinglanguage,enhancingscalabilityandmaintenance.2)Triggersenableautomaticfunctionexecutionone

Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version
Chinese version, very easy to use

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
