zoukankan      html  css  js  c++  java
  • spring-boot和redis的缓存使用

    1.运行环境

    开发工具:intellij idea

    JDK版本:1.8

    项目管理工具:Maven 4.0.0

    2.Maven Plugin管理

    pom.xml配置代码:

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <project xmlns="http://maven.apache.org/POM/4.0.0"
     3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     5     <modelVersion>4.0.0</modelVersion>
     6 
     7     <groupId>com.goku</groupId>
     8     <artifactId>spring-boot-redis</artifactId>
     9     <version>1.0-SNAPSHOT</version>
    10   <build>
    11     <plugins>
    12       <plugin>
    13         <groupId>org.apache.maven.plugins</groupId>
    14         <artifactId>maven-compiler-plugin</artifactId>
    15         <configuration>
    16           <source>1.7</source>
    17           <target>1.7</target>
    18         </configuration>
    19       </plugin>
    20     </plugins>
    21   </build>
    22 
    23   <!-- Spring Boot 启动父依赖 -->
    24   <parent>
    25     <groupId>org.springframework.boot</groupId>
    26     <artifactId>spring-boot-starter-parent</artifactId>
    27     <version>1.5.6.RELEASE</version>
    28   </parent>
    29 
    30   <dependencies>
    31     <!-- Spring Boot web依赖 -->
    32     <dependency>
    33       <groupId>org.springframework.boot</groupId>
    34       <artifactId>spring-boot-starter-web</artifactId>
    35     </dependency>
    36     <!-- Spring Boot test依赖 -->
    37     <dependency>
    38       <groupId>org.springframework.boot</groupId>
    39       <artifactId>spring-boot-starter-test</artifactId>
    40       <scope>test</scope>
    41     </dependency>
    42     <!-- Spring Boot redis 依赖 -->
    43     <dependency>
    44       <groupId>org.springframework.boot</groupId>
    45       <artifactId>spring-boot-starter-data-redis</artifactId>
    46     </dependency>
    47   </dependencies>
    48 
    49 
    50 </project>
    View Code

    3.application.properties编写

    # REDIS (RedisProperties)
    # Redis数据库索引(默认为0)
    spring.redis.database=0
    # Redis服务器地址
    spring.redis.host=127.0.0.1
    # Redis服务器连接端口
    spring.redis.port=6379
    # Redis服务器连接密码(默认为空)
    spring.redis.password=
    # 连接池最大连接数(使用负值表示没有限制)
    spring.redis.pool.max-active=8
    # 连接池最大阻塞等待时间(使用负值表示没有限制)
    spring.redis.pool.max-wait=-1
    # 连接池中的最大空闲连接
    spring.redis.pool.max-idle=8
    # 连接池中的最小空闲连接
    spring.redis.pool.min-idle=0
    # 连接超时时间(毫秒)
    spring.redis.timeout=0
    View Code

    4.Value序列化缓存方法编写

     1 package com.goku.demo.config;
     2 
     3 
     4 import org.springframework.core.convert.converter.Converter;
     5 import org.springframework.core.serializer.support.DeserializingConverter;
     6 import org.springframework.core.serializer.support.SerializingConverter;
     7 import org.springframework.data.redis.serializer.RedisSerializer;
     8 import org.springframework.data.redis.serializer.SerializationException;
     9 /**
    10  * Created by nbfujx on 2017/11/8.
    11  */
    12 public class RedisObjectSerializer implements RedisSerializer<Object> {
    13     private Converter<Object, byte[]> serializer = new SerializingConverter();
    14     private Converter<byte[], Object> deserializer = new DeserializingConverter();
    15     private static final byte[] EMPTY_ARRAY = new byte[0];
    16 
    17     @Override
    18     public Object deserialize(byte[] bytes) {
    19         if (isEmpty(bytes)) {
    20             return null;
    21         }
    22         try {
    23             return deserializer.convert(bytes);
    24         } catch (Exception ex) {
    25             throw new SerializationException("Cannot deserialize", ex);
    26         }
    27     }
    28 
    29     @Override
    30     public byte[] serialize(Object object) {
    31         if (object == null) {
    32             return EMPTY_ARRAY;
    33         }
    34         try {
    35             return serializer.convert(object);
    36         } catch (Exception ex) {
    37             return EMPTY_ARRAY;
    38         }
    39     }
    40 
    41     private boolean isEmpty(byte[] data) {
    42         return (data == null || data.length == 0);
    43     }
    44 }
    View Code

    5.Redis缓存配置类RedisConfig编写

    添加注解@EnableCaching,开启缓存功能

     1 package com.goku.demo.config;
     2 
     3 import org.springframework.cache.CacheManager;
     4 import org.springframework.cache.annotation.CachingConfigurerSupport;
     5 import org.springframework.cache.annotation.EnableCaching;
     6 import org.springframework.context.annotation.Bean;
     7 import org.springframework.context.annotation.Configuration;
     8 import org.springframework.data.redis.cache.RedisCacheManager;
     9 import org.springframework.data.redis.connection.RedisConnectionFactory;
    10 import org.springframework.data.redis.core.RedisTemplate;
    11 import org.springframework.data.redis.serializer.StringRedisSerializer;
    12 
    13 /**
    14  * Created by nbfujx on 2017-12-07.
    15  */
    16 @SuppressWarnings("SpringJavaAutowiringInspection")
    17 @Configuration
    18 @EnableCaching
    19 public class RedisConfig extends CachingConfigurerSupport {
    20 
    21     @Bean
    22     public CacheManager cacheManager(RedisTemplate<Object, Object> redisTemplate) {
    23         RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
    24         cacheManager.setDefaultExpiration(1800);
    25         return cacheManager;
    26     }
    27 
    28     @Bean
    29     public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
    30         RedisTemplate<Object, Object> template = new RedisTemplate<>();
    31         template.setConnectionFactory(factory);
    32         template.setKeySerializer(new StringRedisSerializer());
    33         template.setValueSerializer(new RedisObjectSerializer());
    34         return template;
    35     }
    36 }
    View Code

    6.Application启动类编写

     1 package com.goku.demo;
     2 
     3 import org.springframework.boot.SpringApplication;
     4 import org.springframework.boot.autoconfigure.SpringBootApplication;
     5 import org.springframework.boot.web.servlet.ServletComponentScan;
     6 
     7 /**
     8  * Created by nbfujx on 2017/11/20.
     9  */
    10 // Spring Boot 应用的标识
    11 @SpringBootApplication
    12 @ServletComponentScan
    13 public class DemoApplication {
    14 
    15     public static void main(String[] args) {
    16         // 程序启动入口
    17         // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
    18         SpringApplication.run(DemoApplication.class,args);
    19     }
    20 }
    View Code

    7.测试用例编写

    实体类User编写

     1 package test.com.goku.demo.model;
     2 
     3 import java.io.Serializable;
     4 
     5 /**
     6  * Created by nbfujx on 2017-12-07.
     7  */
     8 public class User implements Serializable {
     9 
    10     private static final long serialVersionUID = -1L;
    11 
    12     private String username;
    13     private Integer age;
    14 
    15     public User(String username, Integer age) {
    16         this.username = username;
    17         this.age = age;
    18     }
    19 
    20     public String getUsername() {
    21         return username;
    22     }
    23 
    24     public void setUsername(String username) {
    25         this.username = username;
    26     }
    27 
    28     public Integer getAge() {
    29         return age;
    30     }
    31 
    32     public void setAge(Integer age) {
    33         this.age = age;
    34     }
    35 }
    View Code

    测试方法编写,包含缓存字符实体

     1 package test.com.goku.demo;
     2 
     3 import com.goku.demo.DemoApplication;
     4 import org.junit.Test;
     5 import org.junit.runner.RunWith;
     6 import org.slf4j.Logger;
     7 import org.slf4j.LoggerFactory;
     8 import org.springframework.beans.factory.annotation.Autowired;
     9 import org.springframework.boot.test.context.SpringBootTest;
    10 import org.springframework.data.redis.core.RedisTemplate;
    11 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    12 import test.com.goku.demo.model.User;
    13 
    14 import java.io.Serializable;
    15 
    16 /**
    17  * Created by nbfujx on 2017-12-07.
    18  */
    19 @RunWith(SpringJUnit4ClassRunner.class)
    20 @SpringBootTest(classes = DemoApplication.class)
    21 public class TestRedis implements Serializable{
    22 
    23     private final Logger logger = LoggerFactory.getLogger(getClass());
    24 
    25     @Autowired
    26     private RedisTemplate redisTemplate;
    27 
    28     @Test
    29     public void test() throws Exception {
    30         // 保存字符串
    31         redisTemplate.opsForValue().set("数字", "111");
    32         this.logger.info((String) redisTemplate.opsForValue().get("数字"));
    33     }
    34 
    35     @Test
    36     public void testobject() throws Exception {
    37         User user = new User("用户1", 20);
    38         redisTemplate.opsForValue().set("用户1",user);
    39         // 保存对象
    40         User user2= (User) redisTemplate.opsForValue().get("用户1");
    41         this.logger.info(String.valueOf(user2.getAge()));
    42     }
    43 
    44 
    45 }
    View Code

    8.查看测试结果

    字符串测试

    实体测试

     

    9.GITHUB地址

    https://github.com/nbfujx/springBoot-learn-demo/tree/master/spring-boot-redis

  • 相关阅读:
    HTML5第二节
    HTML5在移动端开发的12大特性
    移动端开发遇到的坑
    html5 meta(移动端)介绍及使用
    CSS的margin塌陷(collapse)
    Block Demo
    设计模式之代理
    OC Block网上转载
    GCD之全局、主线程
    Spark SQL中 RDD 转换到 DataFrame
  • 原文地址:https://www.cnblogs.com/nbfujx/p/7994988.html
Copyright © 2011-2022 走看看