Java Cache缓存的用途和用法?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Cache缓存的用途和用法?相关的知识,希望对你有一定的参考价值。
Java Cache缓存的用途和用法是什么? 怎样理解缓存?
下面这个是缓存类的一个方法, 想问下这个Serial_Number有什么作用?
public synchronized static long getSerialNumber(Date date)
long key = date.getTime();
System.out.println("key->" + key);
if (key > Serial_Number)
Serial_Number = key;
System.out.println(Serial_Number);
return key;
else
Serial_Number++;
System.out.println("ff_>" + Serial_Number);
return Serial_Number;
java Cache:可以理解为一个空间,对于那些不经常修改的数据可以在执行一次查询后会将查询结果放在这个空间,之后如果还需要这个数据的话就会从这个空间里去找。。好处当然是节省查询时间。。当然也有弊端--可能造成数据不同步,所以要求是不经常修改的数据才会放在缓存里。。追问
你好, 这个缓存为啥会节省查询时间呢?
追答因为如果查询过一次之后数据会放在缓存里,之后需要该数据时会直接从这个缓存里拿数据的。。
追问好的 谢谢
如果我的值有变化, 但是缓存里的还是旧的值, 它会自动更新吗? 还是怎样才能把最新版本的值存入缓存里面噢?
追答服务器一直运行的情况下你不做任何设置就不会自动更新,这也是我前面提到的不可以将经常更新的数据放在缓存中的原因。但是如果你做了一些设置,更新了数据后如果再有查询的话会跳过缓存,直接从数据库查询,然后再一次的将新查询的数据放在缓存就OK了---对于经常变动的数据如果重复这一操作那么利用缓存技术的话就得不偿失了对吧!目前有许多开源的缓存框架,您可以再网上了解一些
追问好的 很详细, 谢谢了
参考技术A 用来瞬间记录数据的啊 而且是用来做返回值吗springboot-cache缓存和J2cache二级缓存框架(带点漫画)
文章目录
引spring-boot-starter-cache漫画
针对热数据,一般我们会把他放到缓冲里,减轻数据库的压力,针对集群下的缓冲,一般我们会把缓冲放到redis里
spring-boot-starter-cache项目整合demo
项目结构
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 配置好对应缓存对应的配置
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 启动类
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);
}
}
效果展示
访问网址:
http://localhost:8889/hello/hello
redis里面已经有数据了
下次走helloCache接口时,从redis里拿取
demo地址
https://gitee.com/null_751_0808/spring-boot-demo
分支:origin/spring-boot2-cache-manager
引J2Cache漫画
J2Cache整合springboot-demo
项目结构
j2cache配置文件
j2cache.properties
这里不放出来了,主要是配置一级缓存是什么,二级缓存是什么,redis广播通知节点的方式,想看的可以去官网看,或者下载此demo看
我的demo配置
一级缓存用了caffeine,二级缓存用了lettuce(连接redis的)
application.yml 配置对应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);
}
}
效果展示
访问
http://localhost:8889/hello/hello
从源码这里可以看到j2cache缓存
AbstractCacheInvoker doGet方法
demo地址
https://gitee.com/null_751_0808/spring-boot-demo/tree/spring-boot2-j2cache/
分支:origin/spring-boot2-j2cache
原理图
redis订阅与发布
二级缓存框架的连接
参考连接
以上是关于Java Cache缓存的用途和用法?的主要内容,如果未能解决你的问题,请参考以下文章