一、配置pom.xml
<!-- springboot整合redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
二、配置application.yml
#redis单服务器配置 spring: redis: database: 0 host: localhost port: 6379 pool: max-active: 8 max-wait: -1 max-idle: 8 min-idle: 0
三、开启缓存
@SpringBootApplication(scanBasePackages = { "com.wuxi" }) @MapperScan("com.wuxi.dao") @EnableCaching // 开启缓存 public class MySpringApplication { public static void main(String[] args) throws Exception { SpringApplication.run(MySpringApplication.class, args); } }
四、实体类序列化
public class Person implements Serializable { }
五、使用方法
@Autowired private UsersMapper usersMapper; @Cacheable(value="findUser") // key是方法的参数组合 @Override public Users findUser(String name) { System.out.println("从数据库中查询..."); return usersMapper.findUserByName(name); }
@Service public class UsersService { @Autowired private RedisTemplate<Object, Object> redisTemplate; public Users seleectUsers() { Users users = (Users) redisTemplate.opsForValue().get("users"); return users; } public void insertUsers(String name) { Users users = new Users(); users.setName(name); redisTemplate.opsForValue().set("users", users, 10, TimeUnit.SECONDS); } }