查询Redis缓存数据,没有再去查询MySQL

master
e 9 months ago
parent 1d6e2ed0b2
commit dee7e53254

@ -35,6 +35,10 @@
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
</dependencies>
</project>

@ -2,12 +2,14 @@ package com.mashibing.entity;
import lombok.Data;
import java.io.Serializable;
/**
* @author zjw
* @description
*/
@Data
public class Air {
public class Air implements Serializable {
private Long id;

@ -4,8 +4,12 @@ import com.mashibing.entity.Air;
import com.mashibing.mapper.AirMapper;
import com.mashibing.service.AirService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* @author zjw
* @description
@ -13,12 +17,26 @@ import org.springframework.stereotype.Service;
@Service
public class AirServiceImpl implements AirService {
@Autowired
@Resource
private AirMapper airMapper;
@Autowired
private RedisTemplate redisTemplate;
private final String AIR_PREFIX = "air:";
@Override
public Air getById(Long id) {
Air air = airMapper.findById(id);
// 查询Redis缓存之前先去查询一下JVM中的缓存 ConcurrentHashMap 作为JVM缓存
// 查询数据库之前查询Redis中的数据
Air air = (Air) redisTemplate.opsForValue().get(AIR_PREFIX + id);
if(air == null) {
// 查询数据库
air = airMapper.findById(id);
redisTemplate.opsForValue().set(AIR_PREFIX + id,air);
}
return air;
}
}

Loading…
Cancel
Save