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 ...
随机推荐
- lerna管理前端模块实践
最近在工作中使用了 lerna 进行前端包的管理,效率提升了很多.所以打算总结一下最近几个月使用 lerna 的一些心得.有那些不足的地方,请包涵. 该篇文章主要包括在使用 lerna 的一些注意事项 ...
- Helium文档8-WebUI自动化-wait_until等待元素出现
前言 wait_until等待某个条件为真才继续往下执行.默认的超时时间为10s,每0.5查询一次,这俩参数选填.可以设置超时时间和轮询间隔. 可以作为添加后校验元素是否存在的场景 入参介绍 def ...
- Kubernetes K8S之调度器kube-scheduler详解
Kubernetes K8S之调度器kube-scheduler概述与详解 kube-scheduler调度概述 在 Kubernetes 中,调度是指将 Pod 放置到合适的 Node 节点上,然后 ...
- service下载任务
在service开启线程,利用接口更新进度 public class MainActivity extends AppCompatActivity { MyBindService msgService ...
- oracle数据库表空间扩展
//查看表空间情况 SELECT Upper(F.TABLESPACE_NAME) "表空间名",D.TOT_GROOTTE_MB "表空间大小(M)",D.T ...
- D. Kilani and the Game 解析(裸BFS、實作)
Codeforce 1105 D. Kilani and the Game 解析(裸BFS.實作) 今天我們來看看CF1105D 題目連結 題目 給一個\(n\times m\)的地圖,地圖上有幾種格 ...
- Setuptools 【Python工具包详解】
什么是setuptools setuptools是Python distutils增强版的集合,它可以帮助我们更简单的创建和分发Python包,尤其是拥有依赖关系的.用户在使用setuptools创建 ...
- 走在深夜的小码农 Second Day
HTML5 Second Day writer:late at night codepeasant 学习大纲 表格 表格的主要作用 表格主要用于显示.展示数据,因为它可以让数据显示的非常的规整,可读性 ...
- Java学习的第二天
1.今天学习了变量与常量看了大道至简 字节型:byte 1字节 短整型:short 2字节 整型:int 4字节长整型:long 8字节单精度浮点型:float 4字节双精度浮点型:double 8 ...
- websocket报400错误
解决方案看了下讨论区说的方案,问题出现在nginx的配置文件,需要修改nginx.conf文件.在linux终端中敲入vim /etc/nginx/nginx.conf,找到location这个位置, ...