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

master
e 1 year ago
parent 1d6e2ed0b2
commit dee7e53254

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

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

@ -4,8 +4,12 @@ import com.mashibing.entity.Air;
import com.mashibing.mapper.AirMapper; import com.mashibing.mapper.AirMapper;
import com.mashibing.service.AirService; import com.mashibing.service.AirService;
import org.springframework.beans.factory.annotation.Autowired; 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 org.springframework.stereotype.Service;
import javax.annotation.Resource;
/** /**
* @author zjw * @author zjw
* @description * @description
@ -13,12 +17,26 @@ import org.springframework.stereotype.Service;
@Service @Service
public class AirServiceImpl implements AirService { public class AirServiceImpl implements AirService {
@Autowired @Resource
private AirMapper airMapper; private AirMapper airMapper;
@Autowired
private RedisTemplate redisTemplate;
private final String AIR_PREFIX = "air:";
@Override @Override
public Air getById(Long id) { 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; return air;
} }
} }

Loading…
Cancel
Save