Redis在springboot项目的使用
一、在pom.xml配置redis依赖
<!-- redis客户端代码 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- json工具 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
<!-- redis需要用到这个依赖,否则报错 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
二、在common包中自定义一个RedisService以及其实现类
Redis的方法比较复杂,可以将经常使用的抽取成方法,形成工具类,方便调用(使用接口加实现类的方式);调用redis时,如下
@Autowired
private RedisService redisService;
RedisService.java接口
package cn.kooun.common.redis;
import cn.kooun.common.redis.entity.MessageCommon;
/**
* redis service
*/
public interface RedisService {
/**
* 添加
*
* @param key
* @param value
* @return
*/
boolean set(final String key, Object value);
/**
* 添加 有生命周期
*
* @param key
* @param value
* @param expireTime
* @return
*/
boolean set(final String key, Object value, Long expireTime);
/**
* 获取
*
* @param key
* @return
*/
Object get(String key);
/**
* 删除
*
* @param key
*/
void delete(final String key);
/**
* 发送广播消息
* @param topic
* @param body
*/
void sendTopic(String topic, MessageCommon body);
}
实现类RedisServiceImpl.java
package cn.kooun.common.redis.impl;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import cn.kooun.common.redis.RedisService;
import cn.kooun.common.redis.entity.MessageCommon;
/**
* redis工具类
*/
@Service
public class RedisServiceImpl implements RedisService{
@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* 添加
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("all")
@Override
public boolean set(final String key, Object value) {
boolean result = false;
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
return true;
}
/**
* 添加带生命周期
*/
@Override
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
operations.set(key, value, expireTime, TimeUnit.SECONDS);
result = true;
return result;
}
/**
* 获取
*/
@Override
public Object get(final String key) {
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
return operations.get(key);
}
/**
* 删除
*/
@Override
@SuppressWarnings("all")
public void delete(final String key) {
redisTemplate.delete(key);
}
/**
* 发送广播消息
*/
@Override
public void sendTopic(String topic,MessageCommon body) {
body.setConsumerTopic(topic);
redisTemplate.convertAndSend(topic,JSON.toJSONString(body));
}
}
redis广播消息体实体类MessageCommon
package cn.kooun.common.redis.entity;
/**
* redis广播消息体实体类
* @author chenWei
* @date 2019年11月7日 上午10:47:08
*/
public class MessageCommon {
/**对方监听器执行回调的方法名*/
private String method;
/**消息体*/
private String body;
/**消息生产者的消费主题,便于回复消息*/
private String producerTopic;
/**消费者消费的主题*/
private String consumerTopic;
public MessageCommon(String method, String body) {
this.method = method;
this.body = body;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getProducerTopic() {
return producerTopic;
}
public void setProducerTopic(String producerTopic) {
this.producerTopic = producerTopic;
}
public String getConsumerTopic() {
return consumerTopic;
}
public void setConsumerTopic(String consumerTopic) {
this.consumerTopic = consumerTopic;
}
@Override
public String toString() {
return "MessageCommon [method=" + method + ", body=" + body + ", producerTopic=" + producerTopic
+ ", consumerTopic=" + consumerTopic + "]";
}
}
三、redis可视化工具乱码(springboot中添加一个类)
package cn.kooun.common.redis;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* 解决redis可视化工具乱码问题
* @author HuangJingNa
* @date 2019年12月21日 下午3:15:19
*
*/
@Configuration
public class RedisConfigBean {
/**
* redis 防止key value 前缀乱码.
*
* @param factory redis连接 factory
* @return redisTemplate
*/
@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
或
package cn.kooun.core.config;
import java.lang.reflect.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* redis配置
*
* @author chenWei
* @date 2019年9月12日 上午11:00:27
*
*/
@Configuration
@EnableCaching
//自动注入自定义对象到参数列表
@SuppressWarnings("all")
public class RedisConfig extends CachingConfigurerSupport {
/**
* key的生成策略
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb;
}
};
}
/**
* RedisTemplate配置
* @author chenwei
* @date 2019年7月2日 上午10:31:44
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
// 配置连接工厂
template.setConnectionFactory(factory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jacksonSeial.setObjectMapper(om);
// 值采用json序列化
template.setValueSerializer(jacksonSeial);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置hash key 和value序列化模式
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jacksonSeial);
template.afterPropertiesSet();
return template;
}
}
Redis在springboot项目的使用的更多相关文章
- Docker运行Mysql,Redis,SpringBoot项目
Docker运行Mysql,Redis,SpringBoot项目 1.docker运行mysql 1.1拉取镜像 1.2启动容器 1.3进入容器 1.4开启mysql 1.5设置远程连接 1.6查看版 ...
- springboot(12)Redis作为SpringBoot项目数据缓存
简介: 在项目中设计数据访问的时候往往都是采用直接访问数据库,采用数据库连接池来实现,但是如果我们的项目访问量过大或者访问过于频繁,将会对我们的数据库带来很大的压力.为了解决这个问题从而redis数据 ...
- Docker运行mysql,redis,oracle容器和SpringBoot项目
dokcer运行SpringBoot项目 from frolvlad/alpine-oraclejdk8:slim VOLUME /tmp ADD target/demo-0.0.1-SNAPSHOT ...
- SpringBoot + Mybatis + Redis 整合入门项目
这篇文章我决定一改以往的风格,以幽默风趣的故事博文来介绍如何整合 SpringBoot.Mybatis.Redis. 很久很久以前,森林里有一只可爱的小青蛙,他迈着沉重的步伐走向了找工作的道路,结果发 ...
- Spring-Boot项目中配置redis注解缓存
Spring-Boot项目中配置redis注解缓存 在pom中添加redis缓存支持依赖 <dependency> <groupId>org.springframework.b ...
- 使用外部容器运行spring-boot项目:不使用spring-boot内置容器让spring-boot项目运行在外部tomcat容器中
前言:本项目基于maven构建 spring-boot项目可以快速构建web应用,其内置的tomcat容器也十分方便我们的测试运行: spring-boot项目需要部署在外部容器中的时候,spring ...
- SpringBoot01 InteliJ IDEA安装、Maven配置、创建SpringBoot项目、属性配置、多环境配置
1 InteliJ IDEA 安装 下载地址:点击前往 注意:需要下载专业版本的,注册码在网上随便搜一个就行啦 2 MAVEN工具的安装 2.1 获取安装包 下载地址:点击前往 2.2 安装过程 到官 ...
- 关于springboot项目中自动注入,但是用的时候值为空的BUG
最近想做一些web项目来填充下业余时间,首先想到了使用springboot框架,毕竟方便 快捷 首先:去这里 http://start.spring.io/ 直接构建了一个springboot初始化的 ...
- SpringBoot 项目打包后运行报 org.apache.ibatis.binding.BindingException
今天把本地的一个SpringBoot项目打包扔到Linux服务器上,启动执行,接口一访问就报错,但是在本地Eclipse中启动执行不报错,错误如下: org.apache.ibatis.binding ...
随机推荐
- Flask实现群聊
后端 from geventwebsocket.handler import WebSocketHandler from gevent.pywsgi import WSGIServer from ge ...
- 对json数组按照id精确查询并修改值
//json数组,里面有一个id等于5的,班级的标识和名称不是该班级,通过id把班级信息修改为指定的信息 var zNodes=[ { id:1, classid:1, className:" ...
- Jenkins集成appium自动化测试(Windows篇)
一,引入问题 自动化测试脚本绝大部分用于回归测试,这就需要制定执行策略,如每天.代码更新后.项目上线前定时执行,才能达到最好的效果,这时就需要进行Jenkins集成. 不像web UI自动化测试可以使 ...
- golang拾遗:为什么我们需要泛型
从golang诞生起是否应该添加泛型支持就是一个热度未曾消减的议题.泛型的支持者们认为没有泛型的语言是不完整的,而泛型的反对者们则认为接口足以取代泛型,增加泛型只会徒增语言的复杂度.双方各执己见,争执 ...
- rabbitmq--通配符模式Topics
topic模式也称为主题模式,其实他相对于routing模式最大的好处就是他多了一种匹配模式的路由,怎么理解匹配呢,其实就相当于我们之前正则的.*这种,不过他的匹配机制可能不是这种(其实除了匹配规则外 ...
- phpstorm 注解路由插件
idea-php-annotation-plugin 设置 插件 搜索 安装 重启
- Python常用模块之random和time
常用模块: time: 分为三种格式: 1.时间戳:从1970年1月1日0点0分0秒到现在经过的秒数 用于时间间隔的计算 import time print(time.time()) 2.字符串显示时 ...
- stm32与红外遥控器(NEC协议)
1.器件简介 本次测试采用R903V1红外接收头与NEC协议的红外遥控器,接收头原理图如下: 器件的供电电压VCC在2.7V~5.5V之间,输出电压VOUT正常在0.2v ~(VCC-0.3±0.2) ...
- 脑桥Brain-Pons
date: 2014-02-01 15:30:11 updated: 2014-02-01 15:30:11 [一] "2025.7.3.Brain-Pons?Expeiment?Under ...
- 走在深夜的小码农 Fifth Day
Css3 Fifth Day writer:late at night codepeasant 学习大纲: 一.css三大特性 1.层叠性 相同选择器给设置相同的样式,此时一个样式就会覆盖(层叠) ...