After that, I summarized the knowledge points of springboot and cache, and quickly mastered them

Java Web Development It was included in three columns at the same time
45 articles 20 subscriptions
5 articles 2 subscription
62 articles 42 subscriptions

This chapter brings you the learning of springboot and cache. At the same time, a very detailed video has been recorded. If it is difficult to read the document, you can learn in combination with the video to help you quickly master sringboot and cache.

catalogue

1、 Jsr107

  2、 Spring cache abstraction

  3、 Several important concepts & cache annotation

4、 Cache usage

5、 Integrating redis to realize caching

6、 Consolidate an instance


IJSR107

Java CachingDefinedfiveCore interfaces areCachingProvider, CacheManager, Cache, Entry AndExpiry

CachingProvider Defines how to create, configure, acquire, manage, and control multiple CacheManager 。 An application can access multiple at run time CachingProvider
CacheManager Defines how to create, configure, acquire, manage, and control multiple uniquely named Cache these Cache Exist in CacheManager In the context of. One CacheManager By only one CachingProvider Owned.
Cache Is a similar Map Data structure and temporary storage for Key Is the value of the index. One Cache By only one CacheManager Owned.
Entry Is a stored in Cache Medium key-value yes.
Expiry Each stored in Cache Entries in have a defined validity period. Once this time is exceeded, the entry is expired. Once expired, entries will not be accessible, updated, or deleted. Cache validity can be ExpiryPolicy set up.

 IISpringCache abstraction

Springfromthree point oneStart definingorg.springframework.cache.Cache

andorg.springframework.cache.CacheManagerInterface to unify different caching technologies;

And support the use ofJCacheJSR-107)AnnotationSimplify our development;

Cache The interface is defined by the component specification of the cache, including various operation sets of the cache;
Cache Under interface Spring Provides a variety of xxxCache Realization of; as RedisCache EhCacheCache , ConcurrentMapCache Etc;
Every time a method that requires caching is called, Spring It will check whether the specified target method of the specified parameter has been called; If yes, get the result of the method call directly from the cache. If not, call the method and cache the result and return it to the user. The next call is taken directly from the cache.
use Spring When caching abstractions, we need to pay attention to the following two points;

oneDetermine the methods that need to be cached and their caching policies

two. read the data stored in the previous cache from the cache

 

 3、 Several important concepts&Cache annotation

 

SpELGrammaticalcacheformat

4、 Cache usage

one . introduction spring-boot-starter-cache modular
two @ EnableCaching Enable cache
three Use cache annotation
four , switch to other cache
Test cache object:

5、 IntegrationredisImplement cache

one introduce spring-boot-starter-data- redis spring-data- redis

  <groupId>redis.clients</groupId>
<
artifactId>jedis</artifactId>

two      to configureredisConnection addressspring.redis.host=192.168.0.108

three      useReditTemplateoperationredis

one redisTemplate.opsForValue ();// Operation string
two redisTemplate.opsForHash ();// operation hash
three redisTemplate.opsForList ();// operation list
four redisTemplate.opsForSet ();// operation set
five redisTemplate.opsForZSet ();// Orderly operation set

Redisconfig implementation:

@Configuration
public class RedisConfig {
//Expiration time
private Duration timeToLive = Duration.ofDays(1);

@Bean
public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory){
RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(timeToLive)
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
.disableCachingNullValues();

RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
.cacheDefaults(configuration).transactionAware().build();
return redisCacheManager;
}

@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(keySerializer());
template.setHashKeySerializer(keySerializer());
template.setValueSerializer(valueSerializer());
template.setHashValueSerializer(valueSerializer());

return template;
}


private RedisSerializer<String> keySerializer(){
return new StringRedisSerializer();
}

private RedisSerializer<Object> valueSerializer(){
return new GenericJackson2JsonRedisSerializer();
}
}

Configuration of application.properties:

spring.datasource.username=spring
spring.datasource.password=spring

#Enable hump naming matching rules
mybatis.configuration.map-underscore-to-camel-case=true

logging.level.com.dahaiwuliang.cache.mapper=debug

#Redis connection
spring.redis.host=192.168.0.108

6、 Consolidate an instance

*Operation process of cacheable
*1. Before the method runs, first go to the cache and find the cache by value. If it is not obtained for the first time, it will be created
*2. Go to the cache to find the entry and use a key. By default, the parameter of the method is used
*Keys are created according to certain rules and are generated by using simpleerator by default
*Generation policy for simpleerator:
*If there are no parameters, key = new simplekey();
*If there is a parameter, key = the value of the parameter
*If there are multiple parameters: key = new simplekey (params);
*
*3. If found, return directly; Call the target method if it is not found
*4. Put the results returned by the target method into the cache
*
*  cacheNames/value:
*Specify the name of the cache component (CACHE) and which cache to put the returned results of the method. It is an array method. You can specify multiple caches
*
*  key:
*The key in the entry is generated by using the simpleerator by default;
*You can also write a spel expression to generate #a0 #p0 #root.args [0] #id
*erator: the generator of the key. You can customize one
*
*CacheManager: Specifies the cache manager
*
*Condition: Specifies that the cache is only cached if the conditions are met
*
*Unless: negative cache, just opposite to condition
*
*Sync: whether to use asynchronous mode

Controller layer:

@RestController
public class EmployeeController {

@Autowired
EmployeeService employeeService;

@GetMapping("/getEmployee")
public Employee getEmployee(Integer id){
Employee employee = employeeService.getEmp(id);
return employee;
}

@GetMapping("/updateEmployee")
public Employee update(Employee employee){
Employee emp = employeeService.updateEmp(employee);
return emp;
}

@GetMapping("/deleteEmployee")
public String deleteEmp(Integer id){
employeeService.deleteEmp(id);
return "success";
}

@GetMapping("/emp/{lastName}")
public Employee getEmployeeByLastName(@PathVariable("lastName") String lastName){
return employeeService.getEmployeeByLastName(lastName);
}
}

Service layer:

public Employee getEmp(Integer id){
System.out.println ("query" + ID + "employee");
Employee employee = employeeMapper.getEmpById(id);
Cache cache = cacheManager.getCache("emp");
cache.put("emp:"+id,employee);
return employee;
}


/**
*@ cacheput: call method and update cache
*The data of the database is modified and the cache is updated at the same time
*Operating mechanism:
*1. Call the target method first;
*2. Cache the results of the target method
*/
@CachePut(/*value = "emp",*/key="#result.id")
public Employee updateEmp(Employee employee){
System.out.println("update:"+employee);
employeeMapper.updateEmp(employee);
return employee;
}

/**
*@ cacheevict: clear cache
*Allentries = true clears all data in this cache
*Beforeinvocation = true means that the cache emptying operation is performed before the method is executed. The cache will be cleared regardless of whether the method is abnormal or not
*/
@CacheEvict(/*value = "emp",*/key = "#id"/*,allEntries = true*/,beforeInvocation = true)
public void deleteEmp(Integer id){
System.out.println("deletEmp:"+id);
//employeeMapper.deleteEmpById(id);
int a = 10/0;
}

/**
*@ caching defines complex caching rules
*/
@Caching(
cacheable = {
@Cacheable(/*value = "emp",*/key = "#lastName")
},
put = {
@CachePut(/*value = "emp",*/key = "#result.id")
}

)
public Employee getEmployeeByLastName(String lastName){
System.out.println("getEmployeeByLastName:"+lastName);
return employeeMapper.getEmpByLastName(lastName);
}
}

Well, the explanation is over. My friends like, collect and comment. I'll walk up three times with one button. See you next time~~

emoticon
Insert expression
Relevant recommendations More similar content
©️ 2020 CSDN Skin theme: technical blackboard Designer: CSDN official blog Return to home page
Paid inelement
Payment with balance
Click retrieve
Code scanning payment
Wallet balance 0

Deduction Description:

1. The balance is the virtual currency of wallet recharge, and the payment amount is deducted according to the ratio of 1:1.
2. The balance cannot be purchased and downloaded directly. You can buy VIP, c-coin package, paid column and courses.

Balance recharge