springBoot+redis(StringRedisTemplate)
安装学习redis找---菜鸟教程
1.添加依赖
<!-- 引入redis依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.写配置文件 密码是默认的
spring:
redis:
#redis数据库地址
host: localhost
port: 6379
password:
timeout: 1000
#redis数据库索引,默认0
database: 1
3. 向redis中存放数据
@Service @Transactional public class UserServiceImpl implements UserService{ @Autowired private StringRedisTemplate redisTemplate; @Autowired private UserMapper userMapper; @Override public int addUser(User user) { int i = userMapper.insert(user); if(i>0){ redisTemplate.opsForValue().set("user : "+user.getUserId(), JsonUtils.objectToJson(user)); } return i; } }
4.向redis中获取数据,如果没有就更新数据
@Override public UserDomain findUser(int userId){ UserDomain result = JsonUtils.jsonToPojo(redisTemplate.opsForValue().get("user : "+userId),User.class); if(result == null){ result = userMapper.findUser(userId); redisTemplate.opsForValue().set("user : "+result.getUserId(), JsonUtils.objectToJson(result)); } return result; }