springboot-cache cache and J2cache second level cache framework (with a little comic)

Article Directory

Citing spring-boot-starter-cache comics

For hot data, we generally put it in the buffer to reduce the pressure on the database. For the buffer under the cluster, we generally put the buffer in redis
Insert picture description here
Insert picture description here

spring-boot-starter-cache project integration demo

Project structure

Insert picture description here

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>
</project>

RedisConfig.java configures the configuration corresponding to the corresponding cache

package com.example.demo.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;

@EnableCaching
@Configuration
public class RedisConfig {
    @Autowired
    RedisConnectionFactory redisConnectionFactory;
    @Bean
    public CacheManager cacheManager() {
        // 设置缓存有效期1小时
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(1))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer((new StringRedisSerializer())))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer((new GenericJackson2JsonRedisSerializer())))
                .computePrefixWith((name)->name+":");
        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory))
                .cacheDefaults(redisCacheConfiguration).build();
    }
}

HelloRespDTO.java

package com.example.demo.dto;

import java.io.Serializable;

public class HelloRespDTO implements Serializable {

    private String name;

    private String address;

    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

HelloService.java

package com.example.demo.service;

import com.example.demo.dto.HelloRespDTO;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class HelloService {

    @Cacheable(cacheNames = "employee",key = "'detail'+#id")
    public HelloRespDTO helloCache(String id){
        HelloRespDTO hello = new HelloRespDTO();
        hello.setName("ben");
        hello.setAddress("广州市白云区");
        hello.setAge(18);
        return hello;
    }

    @CacheEvict(value = "employee",key = "'detail'+#id")
    public HelloRespDTO helloClear(String id){
        HelloRespDTO hello = new HelloRespDTO();
        hello.setName("ben");
        hello.setAddress("广州市白云区");
        hello.setAge(18);
        return hello;
    }
}

HelloController.java

package com.example.demo.controller;

import com.example.demo.dto.HelloRespDTO;
import com.example.demo.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @GetMapping("/hello")
    public HelloRespDTO hello(){
        String id="1";
        HelloRespDTO helloRespDTO = helloService.helloCache(id);
        return helloRespDTO;
    }

    @GetMapping("/hello2")
    public HelloRespDTO helloClear(){
        String id="1";
        HelloRespDTO helloRespDTO = helloService.helloClear(id);
        return helloRespDTO;
    }
}

DemoApplication.java startup class

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Show results

Visit URL:

http://localhost:8889/hello/hello
Insert picture description here


There is already data in redis.

Insert picture description here


Next time you use the helloCache interface, take it from redis

demo ruins

https://gitee.com/null_751_0808/spring-boot-demo
分支:origin/spring-boot2-cache-manager
Insert picture description here

Citing J2Cache comics

Insert picture description here


Insert picture description here


Insert picture description here

J2Cache matching springboot-demo

Project structure

Insert picture description here

j2cache configuration file

j2cache.properties
is not released here, mainly to configure what is the first-level cache, what is the second-level cache, and the way of redis broadcast notification nodes. If you want to see, you can go to the official website to see, or download this demo to see
my demo configuration

Insert picture description here


level one The cache uses caffeine, and the second level cache uses letuce (connected to redis)

application.yml configuration corresponds to j2cache

server:
  port: 8889
  servlet:
    context-path: /hello
spring:
  application:
    name: hello
  redis:
    host: 127.0.0.1
    port: 6379
    password:
    database: 2
  cache:
    type: none
j2cache:
  config-location: /j2cache.properties
  redis-client: lettuce
  open-spring-cache: true

caffeine.properties

#########################################
# Caffeine configuration
# [name] = size, xxxx[s|m|h|d]
#########################################

default = 1000, 30m 

HelloService.java

package com.example.demo.service;

import com.example.demo.dto.HelloRespDTO;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class HelloService {

    //加缓存
    @Cacheable(value="employee",key = "'detail'+#id")
    public HelloRespDTO helloCache(String id){
        HelloRespDTO hello = new HelloRespDTO();
        hello.setName("ben");
        hello.setAddress("广州市白云区");
        hello.setAge(18);
        return hello;
    }

    //清缓存
    @CacheEvict(value="employee",key = "'detail'+#id")
    public HelloRespDTO helloClear(String id){
        HelloRespDTO hello = new HelloRespDTO();
        hello.setName("ben");
        hello.setAddress("广州市白云区");
        hello.setAge(18);
        return hello;
    }
}

HelloRespDTO.java

package com.example.demo.dto;


import java.io.Serializable;

public class HelloRespDTO implements Serializable {

    private String name;

    private String address;

    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

HelloController.java

package com.example.demo.controller;

import com.example.demo.dto.HelloRespDTO;
import com.example.demo.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @GetMapping("/hello")
    public HelloRespDTO hello(){
        String id="1";
        HelloRespDTO helloRespDTO = helloService.helloCache(id);
        return helloRespDTO;
    }

    @GetMapping("/hello2")
    public HelloRespDTO helloClear(){
        String id="1";
        HelloRespDTO helloRespDTO = helloService.helloClear(id);
        return helloRespDTO;
    }

}

DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Show results

access

http://localhost:8889/hello/hello
Insert picture description here


Insert picture description here


From the source code, you can see the j2cache cache
AbstractCacheInvoker doGet method

Insert picture description here

demo ruins

https://gitee.com/null_751_0808/spring-boot-demo/tree/spring-boot2-j2cache/
分支:origin/spring-boot2-j2cache
Insert picture description here

Schematic diagram

Redis subscription and publishing

Insert picture description here


Insert picture description here

Connection of the second-level cache framework

J2Cache
hotkey
redis6.0 client caching

Reference connection

The use of Cache cache in SpringBoot
@Cacheable cache to solve the double colon :: problem