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 ...
随机推荐
- 如何从0到1的构建一款Java数据生成器-第一章
前提 某天晚上老夫在神游时,想起白天公司同事说起的问题,这老表抱怨使用mysql生成大批的随机测试数据太过麻烦,问大家有没有好的工具推荐,老夫对这种事情当然不关心,毕竟我也不知道. 秉承着不懂就要问, ...
- linux(centos8):禁用selinux(临时关闭/永久关闭)
一,selinux的用途 1,什么是selinux SELinux:即安全增强型 Linux(Security-Enhanced Linux) 它是一个 Linux 内核模块,也是 Linux 的一个 ...
- centos8平台使用strace跟踪系统调用
一,strace的用途 strace 是最常用的跟踪进程系统调用的工具. 说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectfore ...
- HTML <del> 标签
HTML <del> 标签 什么是<del> 标签? 定义文档中已被删除的文本. 实例 a month is <del>25</del> 30 day ...
- c++数组的替代品
- CF1430 E. String Reversal(div 2)
题目链接:http://codeforces.com/contest/1430/problem/E 题意:有一串长度为n(n<=2*10^5)由小写字母组成的字符串,求通过相邻交换得到其反转串( ...
- thinkphp数组给js赋值 tp模板把数组赋值给js变量
var arr=transArr({$array|json_encode=true}); function transArr(obj) { var tem=[]; $.each(obj, functi ...
- 跨站资源共享CORS原理深度解析
我相信如果你写过前后端分离的web应用程序,或者写过一些ajax请求调用,你可能会遇到过CORS错误. CORS是什么? 它与安全性有关吗? 为什么要有CORS?它解决了什么目的? CORS是怎样运行 ...
- Bitmap缩放(二)
先得到位图宽高不用加载位图,然后按ImageView比例缩放,得到缩放的尺寸进行压缩并加载位图.inSampleSize是缩放多少倍,小于1默认是1,通过调节其inSampleSize参数,比如调节为 ...
- 【tensorflow】VMware Ubuntu+Tensorflow配置和使用
本文主要是记录配置tf环境和虚拟机时遇到的问题和方法,方便日后再查找(补前三年欠下的技术债) 宿主机环境:win10 64位 宿主机python: anaconda+python3.6 宿主机tens ...