Springboot2.0 + jpa + redis缓存

本文基于Springboot2.0,使用mysql数据库,通过jpa实现orm,再用redis实现数据库的缓存。
目录
1、项目结构
2、环境配置
3、代码
4、测试
5、参考文章


1、项目结构

项目结构

2、环境配置

1)pom.xml

<dependencies>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        
        <!-- 引入Redis缓存 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        
    </dependencies>

2)application.yml
注意:

  • 创建mysql数据库名称为 jpa_redis
  • redis 端口、
  • mysql 数据库账号密码
server:
  port: 8081
 # context-path: /
spring:
  redis:
    host: localhost
    port: 6379
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/jpa_redis
    username: root
    password: abc
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

3、代码

1)SpringBootRedisApplication
注意添加 @EnableCaching

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

@SpringBootApplication
@EnableCaching
public class SpringBootRedisApplication
{
    public static void main(String[] args)
    {
        SpringApplication.run(SpringBootRedisApplication.class, args);
    }
}

2)RedisConfig

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.lang.reflect.Method;
import java.time.Duration;

/**
 * Redis 缓存配置类
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{

    /**
     * 缓存对象集合中,缓存是以 key-value 形式保存的。
     * 当不指定缓存的 key 时,SpringBoot 会使用 SimpleKeyGenerator 生成 key。
     */
//  @Bean
    public KeyGenerator wiselyKeyGenerator()
    {
        // key前缀,用于区分不同项目的缓存,建议每个项目单独设置
        final String PRE_KEY = "test";  
        final char sp = ':';
        return new KeyGenerator()
        {
            @Override
            public Object generate(Object target, Method method, Object... params)
            {
                StringBuilder sb = new StringBuilder();
                sb.append(PRE_KEY);
                sb.append(sp);
                sb.append(target.getClass().getSimpleName());
                sb.append(sp);
                sb.append(method.getName());
                for (Object obj : params)
                {
                    sb.append(sp);
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory)
    {
        // 更改值的序列化方式,否则在Redis可视化软件中会显示乱码。默认为JdkSerializationRedisSerializer
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
                .fromSerializer(new GenericJackson2JsonRedisSerializer());
        RedisCacheConfiguration defaultCacheConfig = RedisCacheConfiguration
                .defaultCacheConfig()
                .serializeValuesWith(pair)      // 设置序列化方式
                .entryTtl(Duration.ofHours(1)); // 设置过期时间

        return RedisCacheManager
                .builder(RedisCacheWriter.nonLockingRedisCacheWriter(factory))
                .cacheDefaults(defaultCacheConfig).build();
    }
}

3)实体类User
注意实现 Serializable 接口

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 用户实体
 */
@Entity
@Table(name = "user")
public class User implements Serializable {
    private static final long serialVersionUID = 1l;
    
    @Id
    @GeneratedValue
    private Integer id;

    @Column(length = 20)
    private String userName;

    @Column(length = 20)
    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

4)UserDao

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import com.cun.entity.User;

/**
 * 用户 dao 接口
 */
public interface UserDao extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User>
{

}

5)UserService

import java.util.List;

import com.cun.entity.User;

public interface UserService
{
    List<User> getAllUsers();

    User findById(Integer pId);
    
    void clearAllUserCache();
    
    void clear(Integer pId);
}

6)UserServiceImpl
cacheNamesvalue 作用一样

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.cun.dao.UserDao;
import com.cun.entity.User;
import com.cun.service.UserService;

@Service
@CacheConfig(cacheNames = "userService")
public class UserServiceImpl implements UserService
{
    @Autowired
    private UserDao userDao;

    /**
     * cacheNames 与 value 定义一样,设置了 value 的值,则类的 cacheNames 配置无效。<br>
     * 使用 keyGenerator ,注意是否在config文件中定义好。
     * @see com.cun.service.UserService#getAllUsers()
     */
    @Override
    @Cacheable(value = "getAllUsers")
//  @Cacheable(value = "getAllUsers", keyGenerator = "wiselyKeyGenerator")
    public List<User> getAllUsers()
    {
        return userDao.findAll();
    }
    
    /**
     * 执行该函数时,将清除以 userService 的缓存,【cacheNames = "userService"】<br>
     * 也可指定清除的key 【@CacheEvict(value="abc")】
     */
    @CacheEvict(value = "getAllUsers")
    public void clearAllUserCache()
    {
        
    }
    
    /**
     * key ="#p0" 表示以第1个参数作为 key
     */
    @Override
    @Cacheable(value="user", key ="#p0")
    public User findById(Integer pId)
    {
        Optional<User> _User = userDao.findById(pId);
        
        return Optional.ofNullable(_User).get().orElse(null);
    }
    
    @CacheEvict(value="user", key ="#p0")
    public void clear(Integer pId)
    {
        
    }
}

7)UserController

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.cun.entity.User;
import com.cun.service.UserService;


/**
 * 参考 https://blog.csdn.net/larger5/article/details/79696562
 */
@RestController
public class UserController
{
    @Autowired
    private UserService userService;

    // http://localhost:8081/all
    @GetMapping("/all")
    public List<User> getAllUsers()
    {
        System.out.println("只有第一次才会打印sql语句");
        return userService.getAllUsers();
    }

    // http://localhost:8081/findById?id=1
    @GetMapping("/findById")
    public User findById(@RequestParam(name = "id")Integer pId)
    {
        return userService.findById(pId);
    }
    
    // http://localhost:8081/clear
    @GetMapping("/clear")
    public void clear()
    {
        userService.clearAllUserCache();
    }
    
    // http://localhost:8081/clearOne?id=1
    @GetMapping("/clearOne")
    public void clear(@RequestParam(name = "id")Integer pId)
    {
        userService.clear(pId);
    }
}

4、测试

启动服务后,可以看到 jpa 框架自动生成 user 表


user表

1)添加测试数据

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.test.context.junit4.*;

import com.cun.SpringBootRedisApplication;
import com.cun.dao.UserDao;
import com.cun.entity.User;


@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=SpringBootRedisApplication.class)
public class AddTester {
    @Autowired
    private UserDao userDao;
    @Test
    public void test()
    {
        User _User = new User();
        _User.setPassword("123");
        _User.setUserName("老王");
        userDao.save(_User);
        
        User _User2 = new User();
        _User2.setPassword("456");
        _User2.setUserName("小李");
        userDao.save(_User2);
    }
}

2)缓存测试
访问 http://localhost:8081/all ,可看到缓存数据

image.png

访问 http://localhost:8081/findById?id=1,可看到缓存数据

image.png

则调用 http://localhost:8081/clear 后,getAllUsers 的缓存将被清除;
则调用 http://localhost:8081/clearOne?id=1 后,user::1 的缓存将被清除。

5、参考文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,546评论 6 507
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,224评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,911评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,737评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,753评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,598评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,338评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,249评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,696评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,888评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,013评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,731评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,348评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,929评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,048评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,203评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,960评论 2 355

推荐阅读更多精彩内容