一、在pom.xml配置redis依赖

  1. <!-- redis客户端代码 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>
  6. <!-- json工具 -->
  7. <dependency>
  8. <groupId>com.alibaba</groupId>
  9. <artifactId>fastjson</artifactId>
  10. <version>1.2.49</version>
  11. </dependency>
  12. <!-- redis需要用到这个依赖,否则报错 -->
  13. <dependency>
  14. <groupId>org.apache.commons</groupId>
  15. <artifactId>commons-pool2</artifactId>
  16. </dependency>

二、在common包中自定义一个RedisService以及其实现类

Redis的方法比较复杂,可以将经常使用的抽取成方法,形成工具类,方便调用(使用接口加实现类的方式);调用redis时,如下

@Autowired

private RedisService redisService;

RedisService.java接口

  1. package cn.kooun.common.redis;
  2. import cn.kooun.common.redis.entity.MessageCommon;
  3. /**
  4. * redis service
  5. */
  6. public interface RedisService {
  7. /**
  8. * 添加
  9. *
  10. * @param key
  11. * @param value
  12. * @return
  13. */
  14. boolean set(final String key, Object value);
  15. /**
  16. * 添加 有生命周期
  17. *
  18. * @param key
  19. * @param value
  20. * @param expireTime
  21. * @return
  22. */
  23. boolean set(final String key, Object value, Long expireTime);
  24. /**
  25. * 获取
  26. *
  27. * @param key
  28. * @return
  29. */
  30. Object get(String key);
  31. /**
  32. * 删除
  33. *
  34. * @param key
  35. */
  36. void delete(final String key);
  37. /**
  38. * 发送广播消息
  39. * @param topic
  40. * @param body
  41. */
  42. void sendTopic(String topic, MessageCommon body);
  43. }

实现类RedisServiceImpl.java

  1. package cn.kooun.common.redis.impl;
  2. import java.util.concurrent.TimeUnit;
  3. import javax.annotation.Resource;
  4. import org.springframework.data.redis.core.RedisTemplate;
  5. import org.springframework.data.redis.core.ValueOperations;
  6. import org.springframework.stereotype.Service;
  7. import com.alibaba.fastjson.JSON;
  8. import cn.kooun.common.redis.RedisService;
  9. import cn.kooun.common.redis.entity.MessageCommon;
  10. /**
  11. * redis工具类
  12. */
  13. @Service
  14. public class RedisServiceImpl implements RedisService{
  15. @Resource
  16. private RedisTemplate<String, Object> redisTemplate;
  17. /**
  18. * 添加
  19. *
  20. * @param key
  21. * @param value
  22. * @return
  23. */
  24. @SuppressWarnings("all")
  25. @Override
  26. public boolean set(final String key, Object value) {
  27. boolean result = false;
  28. ValueOperations<String, Object> operations = redisTemplate.opsForValue();
  29. operations.set(key, value);
  30. return true;
  31. }
  32. /**
  33. * 添加带生命周期
  34. */
  35. @Override
  36. public boolean set(final String key, Object value, Long expireTime) {
  37. boolean result = false;
  38. ValueOperations<String, Object> operations = redisTemplate.opsForValue();
  39. operations.set(key, value, expireTime, TimeUnit.SECONDS);
  40. result = true;
  41. return result;
  42. }
  43. /**
  44. * 获取
  45. */
  46. @Override
  47. public Object get(final String key) {
  48. ValueOperations<String, Object> operations = redisTemplate.opsForValue();
  49. return operations.get(key);
  50. }
  51. /**
  52. * 删除
  53. */
  54. @Override
  55. @SuppressWarnings("all")
  56. public void delete(final String key) {
  57. redisTemplate.delete(key);
  58. }
  59. /**
  60. * 发送广播消息
  61. */
  62. @Override
  63. public void sendTopic(String topic,MessageCommon body) {
  64. body.setConsumerTopic(topic);
  65. redisTemplate.convertAndSend(topic,JSON.toJSONString(body));
  66. }
  67. }

redis广播消息体实体类MessageCommon

  1. package cn.kooun.common.redis.entity;
  2. /**
  3. * redis广播消息体实体类
  4. * @author chenWei
  5. * @date 2019年11月7日 上午10:47:08
  6. */
  7. public class MessageCommon {
  8. /**对方监听器执行回调的方法名*/
  9. private String method;
  10. /**消息体*/
  11. private String body;
  12. /**消息生产者的消费主题,便于回复消息*/
  13. private String producerTopic;
  14. /**消费者消费的主题*/
  15. private String consumerTopic;
  16. public MessageCommon(String method, String body) {
  17. this.method = method;
  18. this.body = body;
  19. }
  20. public String getMethod() {
  21. return method;
  22. }
  23. public void setMethod(String method) {
  24. this.method = method;
  25. }
  26. public String getBody() {
  27. return body;
  28. }
  29. public void setBody(String body) {
  30. this.body = body;
  31. }
  32. public String getProducerTopic() {
  33. return producerTopic;
  34. }
  35. public void setProducerTopic(String producerTopic) {
  36. this.producerTopic = producerTopic;
  37. }
  38. public String getConsumerTopic() {
  39. return consumerTopic;
  40. }
  41. public void setConsumerTopic(String consumerTopic) {
  42. this.consumerTopic = consumerTopic;
  43. }
  44. @Override
  45. public String toString() {
  46. return "MessageCommon [method=" + method + ", body=" + body + ", producerTopic=" + producerTopic
  47. + ", consumerTopic=" + consumerTopic + "]";
  48. }
  49. }

三、redis可视化工具乱码(springboot中添加一个类)

  1. package cn.kooun.common.redis;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.data.redis.connection.RedisConnectionFactory;
  5. import org.springframework.data.redis.core.RedisTemplate;
  6. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
  7. import org.springframework.data.redis.serializer.StringRedisSerializer;
  8. /**
  9. * 解决redis可视化工具乱码问题
  10. * @author HuangJingNa
  11. * @date 2019年12月21日 下午3:15:19
  12. *
  13. */
  14. @Configuration
  15. public class RedisConfigBean {
  16. /**
  17. * redis 防止key value 前缀乱码.
  18. *
  19. * @param factory redis连接 factory
  20. * @return redisTemplate
  21. */
  22. @Bean(name = "redisTemplate")
  23. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  24. RedisTemplate<String, Object> template = new RedisTemplate<>();
  25. template.setConnectionFactory(factory);
  26. template.setKeySerializer(new StringRedisSerializer());
  27. template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
  28. template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
  29. template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
  30. template.afterPropertiesSet();
  31. return template;
  32. }
  33. }

  1. package cn.kooun.core.config;
  2. import java.lang.reflect.Method;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.cache.annotation.CachingConfigurerSupport;
  5. import org.springframework.cache.annotation.EnableCaching;
  6. import org.springframework.cache.interceptor.KeyGenerator;
  7. import org.springframework.context.annotation.Bean;
  8. import org.springframework.context.annotation.Configuration;
  9. import org.springframework.data.redis.connection.RedisConnectionFactory;
  10. import org.springframework.data.redis.core.RedisTemplate;
  11. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  12. import org.springframework.data.redis.serializer.StringRedisSerializer;
  13. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  14. import com.fasterxml.jackson.annotation.PropertyAccessor;
  15. import com.fasterxml.jackson.databind.ObjectMapper;
  16. /**
  17. * redis配置
  18. *
  19. * @author chenWei
  20. * @date 2019年9月12日 上午11:00:27
  21. *
  22. */
  23. @Configuration
  24. @EnableCaching
  25. //自动注入自定义对象到参数列表
  26. @SuppressWarnings("all")
  27. public class RedisConfig extends CachingConfigurerSupport {
  28. /**
  29. * key的生成策略
  30. */
  31. @Bean
  32. public KeyGenerator keyGenerator() {
  33. return new KeyGenerator() {
  34. @Override
  35. public Object generate(Object target, Method method, Object... params) {
  36. StringBuilder sb = new StringBuilder();
  37. sb.append(target.getClass().getName());
  38. sb.append(method.getName());
  39. for (Object obj : params) {
  40. sb.append(obj.toString());
  41. }
  42. return sb;
  43. }
  44. };
  45. }
  46. /**
  47. * RedisTemplate配置
  48. * @author chenwei
  49. * @date 2019年7月2日 上午10:31:44
  50. * @param factory
  51. * @return
  52. */
  53. @Bean
  54. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  55. RedisTemplate<String, Object> template = new RedisTemplate<>();
  56. // 配置连接工厂
  57. template.setConnectionFactory(factory);
  58. //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
  59. Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);
  60. ObjectMapper om = new ObjectMapper();
  61. // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
  62. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  63. // 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
  64. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  65. jacksonSeial.setObjectMapper(om);
  66. // 值采用json序列化
  67. template.setValueSerializer(jacksonSeial);
  68. //使用StringRedisSerializer来序列化和反序列化redis的key值
  69. template.setKeySerializer(new StringRedisSerializer());
  70. // 设置hash key 和value序列化模式
  71. template.setHashKeySerializer(new StringRedisSerializer());
  72. template.setHashValueSerializer(jacksonSeial);
  73. template.afterPropertiesSet();
  74. return template;
  75. }
  76. }

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. 如何从0到1的构建一款Java数据生成器-第一章

    前提 某天晚上老夫在神游时,想起白天公司同事说起的问题,这老表抱怨使用mysql生成大批的随机测试数据太过麻烦,问大家有没有好的工具推荐,老夫对这种事情当然不关心,毕竟我也不知道. 秉承着不懂就要问, ...

  2. linux(centos8):禁用selinux(临时关闭/永久关闭)

    一,selinux的用途 1,什么是selinux SELinux:即安全增强型 Linux(Security-Enhanced Linux) 它是一个 Linux 内核模块,也是 Linux 的一个 ...

  3. centos8平台使用strace跟踪系统调用

    一,strace的用途 strace  是最常用的跟踪进程系统调用的工具. 说明:刘宏缔的架构森林是一个专注架构的博客,地址:https://www.cnblogs.com/architectfore ...

  4. HTML <del> 标签

    HTML <del> 标签 什么是<del> 标签? 定义文档中已被删除的文本. 实例 a month  is <del>25</del> 30 day ...

  5. c++数组的替代品

  6. CF1430 E. String Reversal(div 2)

    题目链接:http://codeforces.com/contest/1430/problem/E 题意:有一串长度为n(n<=2*10^5)由小写字母组成的字符串,求通过相邻交换得到其反转串( ...

  7. thinkphp数组给js赋值 tp模板把数组赋值给js变量

    var arr=transArr({$array|json_encode=true}); function transArr(obj) { var tem=[]; $.each(obj, functi ...

  8. 跨站资源共享CORS原理深度解析

    我相信如果你写过前后端分离的web应用程序,或者写过一些ajax请求调用,你可能会遇到过CORS错误. CORS是什么? 它与安全性有关吗? 为什么要有CORS?它解决了什么目的? CORS是怎样运行 ...

  9. Bitmap缩放(二)

    先得到位图宽高不用加载位图,然后按ImageView比例缩放,得到缩放的尺寸进行压缩并加载位图.inSampleSize是缩放多少倍,小于1默认是1,通过调节其inSampleSize参数,比如调节为 ...

  10. 【tensorflow】VMware Ubuntu+Tensorflow配置和使用

    本文主要是记录配置tf环境和虚拟机时遇到的问题和方法,方便日后再查找(补前三年欠下的技术债) 宿主机环境:win10 64位 宿主机python: anaconda+python3.6 宿主机tens ...