SpringBoot整合Redis缓存

部分引自 www.javaboy.org
新建项目添加四个依赖
因为在springboot2.1.5之后远程连接redis强制要求添加security依赖

image.png

对redis进行配置

# ip
spring.redis.host=127.0.0.1
# 密码
spring.redis.password=12345
# 端口
spring.redis.port=6379
# redis数据库索引
spring.redis.database=0

User实体类 实现 Serializable 可以被序列化

package org.neuedu.redis.bean;

import java.io.Serializable;

public class User implements Serializable {
    private Integer id;
    private String name;
    private String address;

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", address='" + address + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

启动类上添加启用缓存注解

package org.neuedu.redis;

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

@SpringBootApplication
@EnableCaching
public class RedisApplication {

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

}

UserService

package org.neuedu.redis.service;

import org.neuedu.redis.bean.User;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "c1") // 缓存key值前缀
public class UserService {

    @Cacheable // 启用缓存,并以id作为key值存储
    public User findUser(Integer id) {
        System.out.println("findUser>>>>"+id);
        User user = new User();
        user.setId(id);
        user.setName("zhangsan");
        user.setAddress("[email protected]");
        return user;
    }

    @CacheEvict // 当删除后台数据时调用该方法,同步更新缓存数据库 
    public void delete(Integer id) {
        System.out.println("delete>>>>"+id);
    }

    @CachePut(key = "#user.id") // 当修改后台数据时,同步更新缓存数据库
    public User update(User user) {
        System.out.println("update>>>>"+user.getId());
        return user;
    }
}

利用单元测试可以测一下与预想结果是否一致

关于key值的定义还可以根据自己的需要定制,在这里就不做讲解了

你可能感兴趣的:(SpringBoot整合Redis缓存)