【Spring Boot学习之九】缓存支持

环境
  eclipse 4.7
  jdk 1.8
  Spring Boot 1.5.2

一、Spring Boot Cache以及整合EhCache
Spring从3.1开始定义了org.springframework.cache.Cache和org.springframework.cache.CacheManager接口来统一不同的缓存技术;并支持使用JCache(JSR-107)注解简化我们开发;
  Cache接口为缓存的组件规范定义,包含缓存的各种操作集合;
  Cache接口下Spring提供了各种xxxCache的实现;如RedisCache,EhCacheCache ,ConcurrentMapCache等;
  每次调用需要缓存功能的方法时,Spring会检查指定参数的指定的目标方法是否已经被调用过;如果有就直接从缓存中获取方法调用后的结果,如果没有就调用方法并缓存结果后返回给用户。下次调用直接从缓存中获取。

详细参考:Spring Boot Cache使用与整合

二、整合Redis

1、引入依赖

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.wjy</groupId>
    <artifactId>springboot-redis</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.3.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
        <finalName>${project.artifactId}</finalName>
    </build>

</project>

 

2、application.properties配置redis

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

3、service

/**
 * 
 */
package com.wjy.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class RedisService {
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;//操作key-value都是字符串

    @Autowired
    private RedisTemplate redisTemplate;//操作key-value都是对象

    /**
     *  Redis常见的五大数据类型:
     *  stringRedisTemplate.opsForValue();[String(字符串)]
     *  stringRedisTemplate.opsForList();[List(列表)]
     *  stringRedisTemplate.opsForSet();[Set(集合)]
     *  stringRedisTemplate.opsForHash();[Hash(散列)]
     *  stringRedisTemplate.opsForZSet();[ZSet(有序集合)]
     */
    public void setValue(String key,Object value){
        if (value instanceof String)
        {
            stringRedisTemplate.opsForValue().set(key,value.toString());    
        }
        else if (value instanceof List)
        {
            List<String> list = (ArrayList<String>)value;
            for (String s : list)
            {
                stringRedisTemplate.opsForList().leftPush(key, s);
            }
        }
    }
    
    public String getStringKey(String key) {
        return stringRedisTemplate.opsForValue().get(key);
    }
    

}

4、controller

/**
 * 
 */
package com.wjy.controller;

import java.util.ArrayList;
import java.util.List;

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

import com.wjy.service.RedisService;

@RestController
public class IndexController {
    
    @Autowired
    private RedisService redisService;

    @RequestMapping("/setString")
    public String setString(String key,String value) {
        redisService.setValue(key, value);
        return "success";
    }
    
    @RequestMapping("/setList")
    public String setList(String key) {
        List<String> list = new ArrayList<String>();
        list.add("123");
        list.add("456");
        redisService.setValue(key, list);
        return "success";
    }
    
    @RequestMapping("/getKey")
    public String getKey(String key) {
        
        return "success";
    }
    
}

 5、App

package com.wjy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class App {

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

}

 

扩展:在redis中如何存储对象?

使用String类型,将对象转换成json字符串存储,获取对象时,将json串反序列化为对象。

posted @ 2019-07-24 16:59  cac2020  阅读(242)  评论(0编辑  收藏  举报