SpringBoot整合redis缓存

文章目录

  • 1. SpringBoot 自带的缓存
  • 2. 整合Redis

1. SpringBoot 自带的缓存


<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-cacheartifactId>
dependency>
@EnableCaching //开启缓存的功能
public class SpringbootStudyApplication {
/**
* @author [email protected]
* @description @CacheConfig用作指定该类中方法使用的缓存名称,可以用作和其他类的缓存隔离
        * @since 2021/10/19 20:54
        */
@Service
@CacheConfig(cacheNames = "studentsCache")
public class StudentService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * @Cacheable代表该方法开启缓存,缓存的key是方法参数,缓存的value是方法返回值
     */
    @Cacheable
    public Student queryById(Integer id) {
        logger.error(LocalDateTime.now()+"queryById("+id+")");
        Student muzi = new Student();
        muzi.setId(1);
        muzi.setName("木子");
        return muzi;
    }
    /**
     * @CacheEvict可以清除缓存,如果没有指定keyGenerator,则需要指定key,根据指定的key清除缓存
     * @param id
     */
    @CacheEvict(key = "#id")
    public void deleteById(Integer id) {
        logger.warn(LocalDateTime.now()+"deleteById("+id+")");
    }

/**
 * @CachePut用作更新缓存,也要指定缓存的key是多少,方法的返回值作为缓存更新的数据
 * @param student
 * @return
 */
    @CachePut(key = "#student.id")
    public Student editById(Student student) {
        logger.warn(LocalDateTime.now()+"editById()");
        student.setName("木子2");
        return student;
    }
}

2. 整合Redis


<dependency>
<groupId>org.springframework.bootgroupId>
<artifactId>spring-boot-starter-data-redisartifactId>
dependency>
###############################
#### Redis配置 ###############
###############################
#redis端口
spring.redis.port=6379
# Redis所在服务器ip
spring.redis.host=172.16.100.98
# Redis密码(如果不设置,默认为空)
spring.redis.password=softeem
@SpringBootTest
class SpringbootStudyApplicationTests {
@Autowired
private RedisTemplate redisTemplate;
@Test
public void testRedis(){
redisTemplate.opsForValue().set("muzi6","666");
String muzi6 = (String)redisTemplate.opsForValue().get("muzi6");
System.out.println(muzi6);
redisTemplate.delete("muzi6");
}
}

你可能感兴趣的:(spring,boot学习,缓存,spring,boot,redis)