SpringBoot2教程(四)整合缓存Redis

源码地址:https://github.com/q200737056/Spring-Course/tree/master/springboot2Redis

一、项目环境

Java8+Maven3.3.9+SpringBoot2.0.4+Mybatis3+Redis+H2+Eclipse


二、Redis简介

Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库。

Redis具有以下优势

  • 性能极高 – Redis能读的速度是110000次/s,写的速度是81000次/s 。
  • 丰富的数据类型 – Redis支持二进制案例的 Strings, Lists, Hashes, Sets 及 Ordered Sets 数据类型操作。
  • 原子性 – Redis的所有操作都是原子性的,要么成功执行要么失败不执行。单个操作是原子性的。多个操作也支持事务,即原子性,通过MULTI和EXEC指令包起来。
  • 丰富的特性 – Redis还支持 publish/subscribe, 通知, key 过期,master-slave模式的数据备份等特性。
    下载windows版Redis地址:
    https://github.com/MicrosoftArchive/redis/releases
    开启Redis服务

三、H2数据库简介

H2数据库一般适合作为嵌入式数据库使用,而其它的数据库大部分都需要安装独立的客户端和服务器端,如mysql等。

H2的优势

  • H2采用纯Java编写,因此不受平台的限制。
  • H2只有一个jar文件,十分适合作为嵌入式数据库使用。
  • H2提供了一个十分方便的web控制台用于操作和管理数据库内容。

H2数据库下载地址:http://www.h2database.com/html/download.html
运行H2 bin目录下的 h2.bat 或h2w.bat 启动H2数据库。输入http://localhost:8082访问H2数据库的Web Console。如图:


本教程实例中已内嵌H2数据库,不需要单独启用。

四、SpringBoot整合Redis

jar包依赖



         
            com.h2database
            h2
         
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
        
        
            org.apache.commons
            commons-pool2
     

application.yml

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    timeout: 60s
    lettuce:
      pool:
        max-active: 20
        max-wait: 10000ms
        max-idle: 10
        min-idle: 2

springboot2.x默认使用lettuce,如果想要使用jedis,可引入其jar包,修改配置为jedis。Redis默认密码为空,所以不用配置。如果想设置密码,打开Redis根目录下的xx.conf的文件,比如使用了redis.conf配置文件。找到requirepass添加自己想要设置的密码。之后重启Redis服务使之生效。

JavaConfig配置Redis

@Bean
    public RedisTemplate redisTemplate
(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
 
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new 
     Jackson2JsonRedisSerializer(Object.class);
 
        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
 
        template.setValueSerializer(serializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
 
      // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        //  设置缓存的默认过期时间3分,使用Duration设置
        config = config.entryTtl(Duration.ofMinutes(3))  
        // 不缓存空值  
                .disableCachingNullValues();     
 
        // 设置一个初始化的缓存空间set集合
        Set cacheNames =  new HashSet<>();
        cacheNames.add("default");
        cacheNames.add("user");
 
        // 对每个缓存空间应用不同的配置
        Map configMap = new HashMap<>();
        configMap.put("default", config);
        configMap.put("user", config.entryTtl(Duration.ofSeconds(120)));
       // 使用自定义的缓存配置初始化一个cacheManager
        RedisCacheManager cacheManager = 
RedisCacheManager.builder(redisConnectionFactory)
        // 注意这两句的调用顺序,一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
                .initialCacheNames(cacheNames)  
                .withInitialCacheConfigurations(configMap)
                .build();
        return cacheManager;
    }

启动H2数据库内存模式并初始化表数据

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: org.h2.Driver
    #使用TCP/IP的服务器模式
    url: jdbc:h2:tcp://localhost/mem:demo
    username: test
    password: test
@Component
@Order(1)
public class H2dbStart implements ApplicationRunner  {
    @Override
    public void run(ApplicationArguments args) throws Exception {
    try {  
            System.out.println("正在启动h2数据库...");
            Server.createTcpServer().start(); 
            System.out.println("h2数据库启动成功...");
        } catch (SQLException e) {  
            System.out.println("启动h2数据库出错:" + e.toString());  
            e.printStackTrace();  
           throw new RuntimeException(e);  
        }  
    }
}
@Component
public class H2DataInit implements ApplicationRunner {
    @Autowired
    DruidDataSource druidDataSource;
    //初始化h2 数据库表和数据
    @Override
    public void run(ApplicationArguments args) throws Exception {
    
         String sql1 = "CREATE TABLE TEST_USER(id INT NOT NULL AUTO_INCREMENT, "
                + "name VARCHAR(30),password VARCHAR(30), email VARCHAR(100),"
                + "PRIMARY KEY (id))";
         String sql2="INSERT INTO test_user (id, name, password, email) "
                + "VALUES (1, 'admin', 'admin', '[email protected]')";
         String sql3="INSERT INTO test_user (id, name, password, email) "
                + "VALUES (2, 'hehe', 'hehe', '[email protected]')";
         Connection connection = null;
         Statement stmt = null;
         
         try {
            connection = druidDataSource.getConnection();
            stmt = connection.createStatement();
            stmt.addBatch(sql1);
            stmt.addBatch(sql2);
            stmt.addBatch(sql3);
            stmt.executeBatch();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            try {
                 stmt.close();
                 connection.close();
             } catch (Exception e2) {
                 e2.printStackTrace();
             }
            System.out.println("初始化表数据完成。。。");
        }
    }
}

内存模式的数据库,只在服务运行时存在,一旦停止服务,数据库也随之而去。配置servletnew ServletRegistrationBean<>(new WebServlet(),"/h2/*"),启动服务后,可通过http://localhost:8080/h2/访问h2数据库。

启动类@EnableCaching开启缓存

@SpringBootApplication
@MapperScan("com.springboot2.test4.dao")
@EnableCaching
public class App {
    public static void main( String[] args ){
        SpringApplication.run(App.class, args);
        System.out.println("启动成功。。。。。。。。。。。");
    }
}

业务层@Cacheable,@CachePut,@CacheEvict

@Cacheable(value="user",key="'user'+#id",unless = "#result eq null")
@Override
    public User queryUserById(String id){
        System.out.println("去查询数据库。。。");
        return this.indexDao.queryUserById(Integer.valueOf(id));
    }
@CachePut(value="user",key="'user'+#user.id")
    @Override
    public User updateUser(User user){
         this.indexDao.updateUser(user);
         return user;
    }
@CacheEvict(value="user",key="'user'+#id")
    @Override
    public int deleteUser(String id){
        return this.indexDao.deleteUser(id);
    }

缓存注解的说明可参考本人的上一篇文章SpringBoot2教程(三)整合缓存Ehcache

你可能感兴趣的:(SpringBoot2教程(四)整合缓存Redis)