SpringBoot使用Cache缓存

在pom.xml中引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml中增加redis配置,以本地运行为例,配置如下

spring:
  redis:
    port: 6379
    host: 127.0.0.1

在启动类上加@EnableCaching注解

package com.lzc.cache;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class CacheApplication {

    public static void main(String[] args) {
        SpringApplication.run(CacheApplication.class, args);
    }
}

为了方便演示,直接在Controller中使用缓存,代码如下

package com.lzc.cache.controller;

import com.lzc.cache.dataobject.User;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @GetMapping("/cache1")
    @Cacheable(cacheNames = "user",key = "#id")
    public User user1(@RequestParam Integer id) {
        System.out.println("进来了");
        return new User(id,"lizhencheng");
    }

    /**
     * 清除缓存
     * @param id
     * @return
     */
    @GetMapping("/cache2")
    @CacheEvict(cacheNames = "user",key = "#id")
    public String clearUser(@RequestParam Integer id) {
        System.out.println("清除缓存");
        return "清除成功";
    }

    /**
     * 使用对象中的某个字段作为key
     * @param user
     * @return
     */
    @GetMapping("/cache3")
    @Cacheable(cacheNames = "user",key = "#user.username")
    public User user3(User user) {
        System.out.println("进来了");
        return user;
    }

    /**
     * 当返回结果不为空时进行缓存
     * @param id
     * @return
     */
    @GetMapping("/cache4")
    @Cacheable(cacheNames = "user",key = "#id",unless="#result == null")
    public User user4(@RequestParam Integer id) {
        System.out.println("进来了");
        if(id == 1) {
            return null;
        }
        return new User(id,"lzihenchneg");
    }

}


StringRedisTemplate的基本使用

新建一个JsonUtil工具类

package com.lzc.cache.util;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
    private static ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 转换为json字符串
     * @param object
     * @return
     */
    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            throw new RuntimeException("序列化对象【"+object+"】时出错", e);
        }
    }
    /**
     * 将json字符串转换为对象
     * @param entityClass
     * @param jsonString
     * @param <T>
     * @return
     */
    public static <T> T toBean(Class<T> entityClass, String jsonString){
        try {
            return objectMapper.readValue(jsonString, entityClass);
        } catch (Exception e) {
            throw new RuntimeException("JSON【"+jsonString+"】转对象时出错", e);
        }
    }
}

StringRedisTemplate基本操作如下

package com.lzc.cache;

import com.lzc.cache.dataobject.User;
import com.lzc.cache.util.JsonUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;

@RunWith(SpringRunner.class)
@SpringBootTest
public class CacheApplicationTests {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    public void contextLoads() {

    }

    @Test
    public void test1() {
        User user = new User(1,"李振成");
        stringRedisTemplate.opsForValue().set("user_" + 1, JsonUtil.toJson(user));
    }
    @Test
    public void test2() {
        // 判断key是否存在
        if(stringRedisTemplate.hasKey("user_1")) {
            String result = stringRedisTemplate.opsForValue().get("user_1");
            User user = JsonUtil.toBean(User.class, result);
            System.out.println(user.toString());
        } else {
            System.out.println("不存在的key");
        }
    }
    @Test
    public void test3() {
        User user = new User(2,"张三");
        // 设置缓存为6分钟
        stringRedisTemplate.opsForValue().set("user_" + user.getId(), JsonUtil.toJson(user), 5, TimeUnit.MINUTES);
    }
}

猜你喜欢

转载自blog.csdn.net/lizc_lizc/article/details/81259656