Spring集成Redis,封装RedisService

Redis是一个高性能的key-value数据库,经常使用于搭建缓存系统,提升并发响应速度。Spring集成Redis只需简单配置,本文进一步分享封装的RedisService服务。
java


代码文件git

功能要点github

SpringBoot集成Redisredis

pom.xmlspring

引入Redis依赖spring-boot-starter-data-redis数据库

application.yml缓存

配置Redis服务器host, port服务器

封装RedisService服务并发

RedisService.javaapp

封装Redis调用:RedisTemplate, ValueOperations, ListOperations, HashOperations, SetOperations

单元测试

RedisServiceTest.java

测试封装的Redis功能函数

功能调用

CheckController.java

增长REST接口/chk/cache,调用Redis读写功能

 

代码

Github下载:https://github.com/jextop/StarterApi/


SpringBoot集成Redis

1. 新建SpringBoot项目时,选中Redis,将自动添加Redis依赖。

 image.png

2. 已有SpringBoot项目,能够在pom.xml中直接引用Redis Starter:

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

3. application.yml中配置Redis服务器信息:

spring:
  redis:
    host: 127.0.0.1
    port: 6379
    database: 0
    password:
    timeout: 100
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 10
        min-idle: 0

 

调用Redis功能函数,封装服务RedisService.java

1. StringRedisTemplate对String类型的key和value封装

2. 使用ValueOperations<String, String>对String操做

a) setStr()

b) getStr()

3. ValueOperations<Object, Object>对Object操做

a) set()

b) get()

4. ListOperations<Object, Object>对列表操做

a) lSet()

b) lGet()

5. HashOperations<Object, Object, Object>对哈希表操做

a) hSet()

b) hGet()

6. SetOperations<Object, Object>对集合操做

a) sSet()

b) sGet()

 

单元测试RedisServiceTest.java

 image.png

功能调用

1. 增长RestController:CheckController.java

2. 增长REST接口/chk/cache,调用Redis读写功能

@GetMapping(value = "/chk/cache")
public Object cache(@RequestAttribute(required = false) String ip) {
    // Get a unique key
    String key = String.format("cache_test_%s_%s_缓存", ip, CodeUtil.getCode());

    // Set cache
    redisService.setStr(key, key, 3);

    // Get cache
    String str = redisService.getStr(key);
 
    // Delete key
    redisService.delStr(key);

    return new HashMap<String, Object>() {{
        put("chk", "cache");
        put("msg", str);
        put("status", key.equals(str));
    }};
}

 

REST接口调用RedisService示例

 image.png

相关文章
相关标签/搜索