SoFunction
Updated on 2025-03-08

Three ways to implement caching and summary of problems in Java

Three ways to implement caching in Java

1. HashMap implementation cache

​ It can implement simple local cache, but it is not recommended in actual development. We can simply simulate the implementation of cache.

Step-1: Implement a cache management class

public class LocalCache {
    public static HashMap<String,String> cache = new HashMap<>();
    static {
        String name = ().toString();
        ((1),name);
        ("Data with id 1 is added to cache");
    }
}
// There are static code blocks modified by `static` in the class, which will be executed when the class is loaded. If you don't understand, you can follow the blog// /weixin_62636014/article/details/136851287

Tips:We are herestaticInitialization of the cache has been completed, and you can put the initial data into the cache.

Step-2: Leave the cache management class to Spring for management

@Component
public class LocalCache {
    public static HashMap<String,String> cache = new HashMap<>();
    static {
        String name = ().toString();
        ((1),name);
        ("Data with id 1 is added to cache");
    }
    @PostConstruct
    public void init() {
        String name = ().toString();
        ((2),name);
        ("Data with id 2 is added to cache");
    }
}

Tips: Handing over the cache management class toSpringAfter the management is carried out, add it to the method@PostConstruct, the method can be executed by default, note that the annotation is notSpringThe framework is provided byJava JDKProvided mainly forServletThe annotation of the life cycle is realized inBeanCustomize the operation before initialization

@PostConstructMethod inBeanExecution order in initialization

  • Constructor(Construction method)
  • @Autowired(Dependency injection)
  • @PostConstruct(The initialization method of comments)

Step-3: Write interface test cache

@RequestMapping("test")
public String test(Long id) {
    String name = ((id));
    if (name != null) {
        ("Exist in cache, query cache");
        (name);
        return name;
    }
    ("Do not exist in the cache, query the database");
    // After querying the database operation, the queryDataName method is not written;    // You can match Mybatis and JDBC to query the database yourself. The result is to find out the name from the library;    name = queryDataName(id);
    (name);
    ((id),name);
    return name;
}
public String queryDataName(Long id) {
    String name = ().toString();
    return name;
}

Step-4: Results Display

This is the console output, everyone's randomUUIDInconsistent, I'm just a sample

Data with id 1 is added to the cache
Data with id 2 is added to the cache
Exist in the cache, query the cache
e2eadabe-3c42-4732-b465-e085ea5faf96
Does not exist in the cache, query the database
942ffe92-454f-4046-87e5-53e8b951d2a1

2. Guava local cache implementation

TipsGuavayesGoogleA set providedJavaToolkit,Guava CacheIt is a very complete local cache mechanism (JVMCache), tool classes are commonly used methods for packaging, and you don't need to re-create wheels to save developers time. We generally need to know how to use them. Its design comes fromCurrentHashMap, the cached values ​​stored therein can be cleaned up according to various strategies and maintain high concurrent read and write performance.

GuavaProvide the following capabilities

  • gather [collections]
  • cache [caching]
  • Native type support [primitives support]
  • Concurrency library [concurrency libraries]
  • General Annotations [common annotations]
  • String processing [string processing]
  • I/O etc.

Step-1: Importing guava dependencies

<dependency>
            <groupId></groupId>
            <artifactId>guava</artifactId>
            <version>32.1.3-jre</version>
        </dependency>

Step-2: Create a simple cache management class using guava

For the convenience of display, this is used5Cache retention time in seconds.

import ;
import ;
import ;
import ;
@Component
public class GuavaLocalCache{
    private Cache&lt;String,String&gt; fiveSecondCache = ()
        //Set the initial cache size, it should be set reasonably, and the capacity will be expanded in the future        .initalCapacity(10)
        //Maximum value        .maximumSize(100)
        //Concurrent number setting        .concurrencyLevel(5)
        //Cached expiration time, expires 5 seconds after writing        .expireAfterWrite(5,)
        //Statistics of cache hit rate        .recordStats()
        .build()
    public Cache&lt;String,String&gt; getFiveSecondCache() {
        return fiveSecondCache;
    } // Here is to get the cache object.    public void setFiveSecondCache(Cache&lt;String,String&gt; fiveSecondCache) {
         = fiveSecondCache;
    }
}

Step-3: Use guava cache and try to count hits

public class test {
    @Autowired
    private GuavaLocalCache guavaLocalCache;
    @RequestMapping("guavaTest")
    public String guavaTest(Long id) {
        // Get cache        Cache&lt;String,String&gt; fiveSecondCache = ();
        // Get object from cache        String nameCache = ((id));
        // Exist in the cache        if (nameCache != null) {
            ("Cached Hit:"+ nameCache + "," + getCacheStats(fiveSecondCache));
            return nameCache;
        }
        // Save data into cache        ("Cached Miss," + getCacheStats(fiveSecondCache));
        nameCache = id + "-" + ().toString();
        ((id),nameCache);
        return nameCache;
    }
    public String getCacheStats(Cache&lt;String,String&gt; cahce) {
        CacheStats stats = ();
        return "Buffer hit rate:"+() +"Cleared buffer count:" + ();
    }
}

3. Use redis to implement cache

TipsRedis(Full name:Remote Dictionary ServerRemote Dictionary Service) is an open source usageANSI CLanguage: Writing, supporting network, logging type that can be memory-based or persistent,Key-Valuedatabase .Redis It is generally used for caching, and it is actually a kind of database (Non-relational database), which can store frequently used data, which is what we call cache. The official data is,Redis Can achieve10w+ofQPS(Query speed per second).

Tips: WhyRedisSpeed ​​ratioMysqlWait for this kind of data to be fast?

BecauseRedisWhat is stored iskey-valuesThe time complexity of the data in the format isO(1), that is, directlykey Query the correspondingvalue . AndMysql The underlying implementation of the database isB+The time complexity isO(logn)

The most important point is that the data in the database is stored indiskin, andRedisIt is stored inMemoryAmong them, their speed gap is self-evident. butRedis Supports persistent storage

Step-1: Import Redis Dependencies

        <dependency>
            <groupId></groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

existSpringBootAdd settings to the configuration file, I'm usingymlIf you don't have a password, just don't fill it in

  redis:
    # IP address    host: 
    # password    password: XXXXXXXX
    # port, default is 6379    port: 6379
    # Database Index    database: 0
    # Connection timeout    timeout: 10s
    lettuce:
      pool:
        # Minimum idle connection in the connection pool        min-idle: 1
        # Maximum free connection in the connection pool        max-idle: 8
        # Maximum number of database connections to the connection pool        max-active: 8
        # #Maximum blocking waiting time for connection pools (using negative values ​​means there is no limit)        max-wait: -1ms

Step-2: Write a test interface

public class TestRedis{
    // The following StringRedisTemplate is a class inherited from RedisTemplate    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @RequestMapping("/redisTest")
    public String redisCacheTest(Long id){
        String name = ().get((id));
        if (name != null){
            ("Exist in cache, query cache");
            (name);
            return name;
        }
        ("Do not exist in the cache, query the database");
        name = id + "-" + ().toString();
        (name);
        ().set((id),name);
        return name;
    }
}

Step-3: Perform interface testing and use Redis DeskTop Manager to view it

Reference article

  1. 【java cache, redis cache, guava cache】 Several ways to implement cache in java_java cache cache-CSDN blog
  2. One article to get the basics of Redis - Zhihu ()
  3. Selection of Java local cache technology (Guava Cache, Caffeine, Encache) - Nuggets ()
  4. Super detailed interpretation of MemCache principle (learning only) - Zhihu ()
  5. PostConstruct annotation details and understanding - CSDN Blog
  6. PostConstruct (Java Platform SE 8 ) ()
  7. The use of the Java development tool Guava Cache - Nuggets ()
  8. Introduction and use of Google guava tool classes - Nuggets ()
  9. Redis detailed introduction (lite version)_redis service Lite-CSDN blog
  10. First know Redis, it's enough to read this article

This is the article about the three ways to implement caching in Java. This is all about this article. For more related Java cache content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!