redis在实际开发中的应用
基于springboot项目
本文内容来自:
http://www.macrozheng.com/#/architect/mall_arch_03
https://blog.csdn.net/m0_37499059/article/details/79964717
亲测有效,学习记录!
添加配置
在pom文件中新增Redis相关依赖
<!--redis依赖配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
修改springboot配置文件
配置可以根据自己的实际情况进行调整,不一定非要按下方的配置来,仅供参考。
在application.yml中添加Redis的配置及Redis中自定义key的配置。
在spring节点下添加Redis的配置
redis:
host: localhost # Redis服务器地址
database: 0 # Redis数据库索引(默认为0)
port: 6379 # Redis服务器连接端口
password: # Redis服务器连接密码(默认为空)
jedis:
pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 8 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接
timeout: 3000ms # 连接超时时间(毫秒)
在根节点下添加Redis自定义key的配置
# 自定义redis key
redis:
key:
prefix:
authCode: "portal:authCode:"
expire:
authCode: 120 # 验证码超期时间
添加RedisService接口用于定义一些常用Redis操作
package com.macro.mall.tiny.service;
/**
* redis操作Service,
* 对象和数组都以json形式进行存储
* Created by macro on 2018/8/7.
*/
public interface RedisService {
/**
* 存储数据
*/
void set(String key, String value);
/**
* 获取数据
*/
String get(String key);
/**
* 设置超期时间
*/
boolean expire(String key, long expire);
/**
* 删除数据
*/
void remove(String key);
/**
* 自增操作
* @param delta 自增步长
*/
Long increment(String key, long delta);
}
注入StringRedisTemplate,实现RedisService接口
package com.macro.mall.tiny.service.impl;
import com.macro.mall.tiny.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;
/**
* redis操作Service的实现类
* Created by macro on 2018/8/7.
*/
@Service
public class RedisServiceImpl implements RedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public void set(String key, String value) {
stringRedisTemplate.opsForValue().