How to store data in cache in Java
In Java, there are various caching libraries or frameworks that can be used to store data in a cache. Two popular options are:
Use Ehcache:
Ehcache is a powerful open source Java caching library. Firstly, you must add the Ehcache dependency to your project. Next, create a cache configuration file (ehcache.xml) that defines the properties and rules of the cache. Then, use the Ehcache API to create a cache instance in your code and store data in the cache. Here is an example code:
import net.sf.ehcache.Cache;import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
// 创建缓存管理器
CacheManager cacheManager = CacheManager.create();
// 获取或创建缓存实例
Cache cache = cacheManager.getCache("myCache");
// 将数据存储到缓存中
Element element = new Element("key", "value");
cache.put(element);
// 从缓存中获取数据
Element result = cache.get("key");
Object value = result.getObjectValue();
// 关闭缓存管理器
cacheManager.shutdown();
Using Caffeine:
Caffeine is another popular Java caching library known for its high performance and low latency. To start, you’ll need to add Caffeine as a dependency in your project. Then, in your code, use the Caffeine API to create a cache instance and store data in the cache. Here is an example code snippet:
import com.github.benmanes.caffeine.cache.Cache;import com.github.benmanes.caffeine.cache.Caffeine;
// 创建缓存实例
Cache<String, Object> cache = Caffeine.newBuilder()
.maximumSize(100)
.build();
// 将数据存储到缓存中
cache.put("key", "value");
// 从缓存中获取数据
Object value = cache.getIfPresent("key");
// 清空缓存
cache.invalidateAll();
These are examples of two commonly used Java cache libraries. You can choose the cache solution that suits your project’s needs and store data according to the corresponding API.