In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about how to implement caching in SpringBoot. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.
Brief introduction
Spring defines CacheManager and Cache interfaces to unify different caching technologies. For example, JCache, EhCache, Hazelcast, Guava, Redis, etc. When integrating Cache with Spring, we need to register the Bean of the implemented CacheManager. Spring Boot uses SimpleCacheConfiguration by default, even with caching implemented by ConcurrentMapCacheManager.
CacheManager: cache manager, managing various cache components CacheManager description SimpleCacheManager uses checkpoint Collection to store cache, mainly for testing ConcurrentMapCacheManager using ConcurrentMap storage cache NoOpCacheManager only for testing, not actual storage cache EhCacheCacheManager using EhCache as cache technology GuavaCacheManager using Guava as cache technology HazelcastCacheManager using Hazelcast as cache technology JCacheCacheManager supporting JCache (JSR-107) standard implementation as cache technology RedisCacheManager using Redis as cache technology Cache Note 1. @ CacheConfig
@ CacheConfig: it is mainly used to configure some common cache configurations that will be used in this class.
Here @ CacheConfig (cacheNames = "users"): the content returned in the data access object is configured to be stored in a cache object named users, or we can define it directly through the name of the cache set configured by @ Cacheable without using this annotation.
2. @ Cacheable
@ Cacheable: mainly for method configuration, the result can be cached according to the request parameters of the method. At the same time, when querying, it will get it from the cache first, and then initiate access to the database if it does not exist. The annotation mainly has the following parameters:
Value, cacheNames: two equivalent parameters (cacheNames is added to Spring 4 as an alias for value) to specify the collection name of the cache store. With the addition of @ CacheConfig in Spring 4, the value attribute that is required in Spring 3 has become optional.
Key: the key value of the cache object stored in the Map collection, which is not required. By default, all the parameters of the function are combined as the key value. If you configure it yourself, you need to use the SpEL expression, such as @ Cacheable (key = "# p0"): use the first parameter of the function as the cached key value. For more information on the SpEL expression, please see the official documentation.
Condition: the condition for caching objects is not required. You also need to use SpEL expressions. Only the content that meets the expression conditions will be cached, for example: @ Cacheable (key = "# p0", condition = "# p0.length () < 3"), which means that the first parameter will only be cached if the length of the first parameter is less than 3. If you make this configuration, the AAA users above will not be cached. Readers can try it by themselves.
Unless: another cache condition parameter, which is not required, requires the use of SpEL expressions. What distinguishes it from the condition parameter is its timing, which is judged after the function has been called, so it can judge the result.
KeyGenerator: used to specify the key generator, not required. To specify a custom key generator, we need to implement the org.springframework.cache.interceptor.KeyGenerator interface and use this parameter to specify it. It is important to note that this parameter and key are mutually exclusive.
CacheManager: used to specify which cache manager to use, not required. It needs to be used only if there are multiple.
CacheResolver: used to specify which cache parser to use, not required. Need to go through
Org.springframework.cache.interceptor.CacheResolver interface to implement your own cache parser and specify it with this parameter.
3. @ CachePut
@ CachePut: configured on the method, it can be cached according to the conditions defined by the parameters. Unlike @ Cacheable, it does not check whether the previously executed result exists in the cache, but executes the method every time, and stores the execution result in the cache in the form of key-value pairs, so it is mainly used for data addition and modification operations. Its parameters are similar to @ Cacheable. For more information, please see the parsing of @ Cacheable parameters above.
4. @ CacheEvict
@ CacheEvict: configured on the function, usually used in the delete method to remove the corresponding data from the cache. In addition to the same parameters as @ Cacheable, it has the following two parameters:
AllEntries: optional. Default is false. When true, all data is removed.
BeforeInvocation: optional, defaults to false, and removes data after the method is called; when true, the data is removed before the method is called.
Set up Spring Boot default cache 1. Enable cache support
Add @ EnableCaching to the startup class to enable cache support for automatic scanning.
@ SpringBootApplication@EnableCaching / / enable caching function public class CacheApplication {public static void main (String [] args) {SpringApplication.run (CacheApplication.class, args);}} 2. Add spring-boot-starter-cache dependency
Add spring-boot-starter-cache dependencies to pom.xml.
Org.springframework.boot spring-boot-starter-cache3. Prepare data to simulate database data / * data factory, simulate database data * * @ author star * * / public class DataFactory {private DataFactory () {} private static List userDtoList; static {/ / initialize collection userDtoList = new ArrayList (); UserDto user = null; for (int I = 0; I < 10; iTunes +) {user = new UserDto () User.setName ("star" + I); user.setAge ("2" + I); userDtoList.add (user);}} public static List getUserDaoList () {return userDtoList }} write cache business code / * UserRepository * * @ author star * * / @ Repositorypublic class UserRepository {/ * to get user information (here is simulated data) * / public UserDto getUser (String username) {UserDto user = getUserFromList (username); return user } / * Delete user information * / public List deleteUser (String username) {List userDaoList = DataFactory.getUserDaoList (); userDaoList.remove (getUserFromList (username)); return userDaoList;} / * New data * / public List save (String username) {/ / add to the collection List userDaoList = DataFactory.getUserDaoList () For (UserDto userDto: userDaoList) {/ / cannot add the same data repeatedly: if (Objects.equals (userDto.getName (), username)) {return userDaoList;}} UserDto user = new UserDto (); user.setName (username); user.setAge ("50"); userDaoList.add (user); return userDaoList } / * filter username data from the simulated data set * / private UserDto getUserFromList (String username) {List userDaoList = DataFactory.getUserDaoList (); for (UserDto user: userDaoList) {if (Objects.equals (user.getName (), username)) {return user;}} return null }} / * UserService * * @ author star * * / @ Service@CacheConfig (cacheNames = "users") / / specify the cache name, which is the global public class UserService {@ Autowired private UserRepository userRepository in this class / * the cache key is the data of username into the cache users. * if key is not specified, the method parameters are saved to the cache as key * / @ Cacheable (key = "# username") public UserDto getUser (String username) {System.out.println ("get data from the database, not read cache"); return userRepository.getUser (username) } / * add or update data in cache * / @ CachePut (key = "# username") public List save (String username) {return userRepository.save (username) } / * remove data from the cache users where key is username * / @ CacheEvict (key = "# username") public List deleteUser (String username) {System.out.println ("Delete data from the database and data in the cache"); return userRepository.deleteUser (username) }} / * CacheResource * * @ author star * * / @ RestController@RequestMapping ("/ api") public class CacheResource {@ Autowired private UserService userService; @ GetMapping ("/ users/ {username}") public ResponseEntity getUser (@ PathVariable String username) {/ / get data UserDto user = userService.getUser (username); return ResponseEntity.ok (user) } @ PutMapping ("/ users/ {username}") public ResponseEntity save (@ PathVariable String username) {List userDtoList = userService.save (username); return ResponseEntity.ok (userDtoList);} @ DeleteMapping ("/ users/ {username}") public ResponseEntity delete (@ PathVariable String username) {List userDtoList = userService.deleteUser (username); return ResponseEntity.ok (userDtoList) }} above is how to implement caching in SpringBoot. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.