一、在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项目的使用的更多相关文章

  1. Docker运行Mysql,Redis,SpringBoot项目

    Docker运行Mysql,Redis,SpringBoot项目 1.docker运行mysql 1.1拉取镜像 1.2启动容器 1.3进入容器 1.4开启mysql 1.5设置远程连接 1.6查看版 ...

  2. springboot(12)Redis作为SpringBoot项目数据缓存

    简介: 在项目中设计数据访问的时候往往都是采用直接访问数据库,采用数据库连接池来实现,但是如果我们的项目访问量过大或者访问过于频繁,将会对我们的数据库带来很大的压力.为了解决这个问题从而redis数据 ...

  3. Docker运行mysql,redis,oracle容器和SpringBoot项目

    dokcer运行SpringBoot项目 from frolvlad/alpine-oraclejdk8:slim VOLUME /tmp ADD target/demo-0.0.1-SNAPSHOT ...

  4. SpringBoot + Mybatis + Redis 整合入门项目

    这篇文章我决定一改以往的风格,以幽默风趣的故事博文来介绍如何整合 SpringBoot.Mybatis.Redis. 很久很久以前,森林里有一只可爱的小青蛙,他迈着沉重的步伐走向了找工作的道路,结果发 ...

  5. Spring-Boot项目中配置redis注解缓存

    Spring-Boot项目中配置redis注解缓存 在pom中添加redis缓存支持依赖 <dependency> <groupId>org.springframework.b ...

  6. 使用外部容器运行spring-boot项目:不使用spring-boot内置容器让spring-boot项目运行在外部tomcat容器中

    前言:本项目基于maven构建 spring-boot项目可以快速构建web应用,其内置的tomcat容器也十分方便我们的测试运行: spring-boot项目需要部署在外部容器中的时候,spring ...

  7. SpringBoot01 InteliJ IDEA安装、Maven配置、创建SpringBoot项目、属性配置、多环境配置

    1 InteliJ IDEA 安装 下载地址:点击前往 注意:需要下载专业版本的,注册码在网上随便搜一个就行啦 2 MAVEN工具的安装 2.1 获取安装包 下载地址:点击前往 2.2 安装过程 到官 ...

  8. 关于springboot项目中自动注入,但是用的时候值为空的BUG

    最近想做一些web项目来填充下业余时间,首先想到了使用springboot框架,毕竟方便 快捷 首先:去这里 http://start.spring.io/ 直接构建了一个springboot初始化的 ...

  9. SpringBoot 项目打包后运行报 org.apache.ibatis.binding.BindingException

    今天把本地的一个SpringBoot项目打包扔到Linux服务器上,启动执行,接口一访问就报错,但是在本地Eclipse中启动执行不报错,错误如下: org.apache.ibatis.binding ...

随机推荐

  1. Android开发教程之密码框右侧显示小眼睛

    现在都说互联网寒冬,其实只要自身技术能力够强,咱们就不怕!我这边专门针对Android开发工程师整理了一套[Android进阶学习视频].[全套Android面试秘籍].[Android知识点PDF] ...

  2. C语言/C++编译环境的设置!有的人还没开始就卡住了!

    本地环境设置 如果您想要设置 C++ 语言环境,您需要确保电脑上有以下两款可用的软件,文本编辑器和 C++ 编译器. 文本编辑器 这将用于输入您的程序.文本编辑器包括 Windows Notepad. ...

  3. 【Luogu】P3005 [USACO10DEC]槽的游戏The Trough Game

    一.题目 题目描述 农夫约翰和贝西又在玩游戏.这个游戏需要很多个槽. 农夫约翰在谷仓里藏起来了N(1<=N<=20)个槽,并且他已经把其中的一些装上了食物.贝西以"在这个表里(表 ...

  4. Helium文档1-WebUI自动化-环境准备与入门

    前言 Helium 是一款 Web 端自动化开源框架,全称是:Selenium-Python-Helium,从名字上就可以看出,Helium 似乎和 Selenium 息息相关,基于Selenium的 ...

  5. 原生JS实现动态折线图

    原生JS实现动态折线图 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> & ...

  6. linux修改环境变量后无法登录

    在登陆界面按Ctrl+Alt+F1(F1~F6), 进入 tty 后登陆账号. 执行以下命令: /usr/bin/sudo /usr/bin/vi /etc/environment 将PATH的值复原 ...

  7. codevs1298, hdu1392 (凸包模板)

    题意: 求凸包周长. 总结: 测试模板. 代码: #include <iostream> #include <cstdio> #include <cstring> ...

  8. pyqt5为控件设置提示信息

    # 显示控件提示消息 import sys from PyQt5.QtWidgets import QHBoxLayout,QMainWindow,QApplication,QToolTip,QPus ...

  9. 将字符串反转的 Java 方法

    Java中经常会用到将字符串进行反转的时候,程序员孔乙己总结了7种反转方法,如下: //方法1 递归方法 public static String reverse1(String s) { int l ...

  10. 一套轻量级销售团队管理系统【CRM】

    项目描述 Hi,大家好,又到了源码分享时间啦,今天我们分享的源码一个<轻量级销售团队管理系统>,这套系统是一套轻量级的CRM系统,基于SSM的SpringBoot架构.这套项目用到很多潮流 ...