1.本地安装redis服务,官网下载。

2.在开发中要使用redis,首先要启动本地redis服务,启动后页面如下:

3.在spring boot项目pom.xml文件中添加Redis需要的依赖包,可在生成springboot项目选择自动引入:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

4.在application-dev.yml(spring cloud)/application.properties(spring boot)配置文件中加入Redis的配置信息:

#此为spring cloud配置文件格式
spring:
  redis:
database: 0
host: 127.0.0.1
port: 6379
password:
timeout: 500
pool:
max-active: 20 # 连接池最大连接数(使用负值表示没有限制
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制
max-idle: 8 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接
##此为spring boot格式配置文件
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=20
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=500

5.创建Redis的配置类,定义序列方式;配置了配置文件,spring boot会自动加载redis

package com.yf.microservice.config;

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.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonAutoDetect; /**
* @Description: Redis配置类
*/ @Configuration
public class RedisConfiguration { @Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
template.setKeySerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}

6.定义一个简单的redis工具类,这里只给到简单的存取方法,Redis封装了很多方法可使用redisTemplate调用,具体哪些方法查看Redis文档

package com.yf.microservice.web.rest.util;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils; /**
* Redis工具类
*/
@Component
public class RedisUtils { @Autowired
private RedisTemplate<String, Object> redisTemplate; /**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 普通缓存获取
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}

7.前面使用@Component注解把RedisUtils类实例化放到spring容器中了,直接使用@Autowired获取对象使用,也可以直接使用RedisTemplate进行调用其他redis封装方法,参考上面写法

 @Autowired
private RedisUtils redisUtil; @Autowired
private RedisTemplate<String, Object> redisTemplate; public String test() {
redisUtil.set("myName", "学不会丶");//存入key -value
redisTemplate.opsForHash().putAll("map1", new
HashMap<String, Object>());//存入map的方法,set,list等方法查看redis文档
return redisUtil.get("myName").toString();//通过key取值
}





Java 在spring cloud中使用Redis,spring boot同样适用的更多相关文章

  1. 译自如何将Spring Cloud应用程序从Spring Boot 1.2迁移到1.3

    前言 笔者第三个Spring Cloud(版本为Spring Boot 1.2)类项目升级最新版本时遇到不少问题,本文内容是作者翻译Spring Cloud官网一位国外友人文章产生. 原文地址: Mi ...

  2. Spring Cloud中负载均衡器概览

    在上篇文章中(RestTemplate的逆袭之路,从发送请求到负载均衡)我们完整的分析了RestTemplate的工作过程,在分析的过程中,我们遇到过一个ILoadBalancer接口,这个接口中有一 ...

  3. Spring Cloud中服务的发现与消费

    之前没注意,微信公众号的图片不能引用到其他地方,本文图片显示不正常,原图在写完博客后已经删了,,,,,,所以本文小伙伴可以移步这里https://mp.weixin.qq.com/s/GoIZdwt5 ...

  4. 服务注册发现consul之二:在Spring Cloud中使用Consul实现服务的注册和发现

    首先安装consul环境,参照之前的文章:<服务注册发现consul之一:consul介绍及安装>中的第一节介绍. Spring Cloud使用Consul的服务与发现 1.导入依赖pri ...

  5. Spring Cloud中Hystrix、Ribbon及Feign的熔断关系是什么?

    导读 今天和大家聊一聊在Spring Cloud微服务框架实践中,比较核心但是又很容易把人搞得稀里糊涂的一个问题,那就是在Spring Cloud中Hystrix.Ribbon以及Feign它们三者之 ...

  6. Spring Cloud中五大神兽总结(Eureka/Ribbon/Feign/Hystrix/zuul)

    Spring Cloud中五大神兽总结(Eureka/Ribbon/Feign/Hystrix/zuul) 1.Eureka Eureka是Netflix的一个子模块,也是核心模块之一.Eureka是 ...

  7. 解决Spring Cloud中Feign第一次请求失败的问题

    在Spring Cloud中,Feign和Ribbon在整合了Hystrix后,可能会出现首次调用失败的问题 com.netflix.hystrix.exception.HystrixTimeoutE ...

  8. 详解Spring Cloud中Hystrix 线程隔离导致ThreadLocal数据丢失

    在Spring Cloud中我们用Hystrix来实现断路器,Zuul中默认是用信号量(Hystrix默认是线程)来进行隔离的,我们可以通过配置使用线程方式隔离. 在使用线程隔离的时候,有个问题是必须 ...

  9. Spring Cloud中Feign如何统一设置验证token

    代码地址:https://github.com/hbbliyong/springcloud.git 原理是通过每个微服务请求之前都从认证服务获取认证之后的token,然后将token放入到请求头中带过 ...

随机推荐

  1. springboot+druid连接池及监控配置

    1. 问题描述 阿里巴巴的数据库连接池Druid在效率与稳定性都很高,被很多开发团队使用,并且自带的Druid监控也很好用,本章简单介绍下springboot+druid配置连接池及监控. 2. 解决 ...

  2. ZIP:Checksum

    Checksum: long getValue() :返回当前的校验和值. void reset() :将校验和重置为其初始值. void update(byte[] b, int off, int ...

  3. 【DFS练习】Pku1950 Dessert-C++

    这道题和这道题很类似. 这里还是说一下坑点,因为前一道题'等式'的加数只有9个,但是这道题目最大到了15,所以在选择不加符号的时候需要判断是用100去乘还是用10去乘就可以了. 基本代码稍微把相关的9 ...

  4. 各类最短路算法基本模板-C++

    原文转自:https://blog.csdn.net/changjiale110/article/details/77394650 感谢. #define Max 0x3f3f3f3f #define ...

  5. iPhone调试移动端webview

    一.模拟器调试 1.启动Xcode 2.选择菜单Xcode - Open Developer Tool - Simulator 3.启动Simulator后,选择Simulator菜单Hardware ...

  6. HBaseCon Asia2019 会议总结

    一.首先会议流程. 1. The current status of HBase 2.The advantage and technology trend of HBase on the cloud ...

  7. .md 文件格式

    # .md 文件怎么编写 > 整理一套常用操作,自己来使用 > ## 标题 >> 写法: \# 这是一个一级标题 \## 这是一个二级标题 \### 这是一个三级标题 \### ...

  8. CentOS 7.3 安装python3

    1.排查 CentOS 7.3 默认安装的是python2,使用命令 python -V 可以看到 python 的版本 Python 2.7.5 然后使用命令 which python 查看一下Py ...

  9. React躬行记(10)——高阶组件

    高阶组件(High Order Component,简称HOC)不是一个真的组件,而是一个没有副作用的纯函数,以组件作为参数,返回一个功能增强的新组件,在很多第三方库(例如Redux.Relay等)中 ...

  10. CF392BTower of Hanoi(记忆化搜索)

    CF392B 记搜好题 预处理 题目给出了将一个盘从x移到y的代价(代码中为a[][]),当我们知道这并不是最优的 就像最短路floyd一样松弛操作预处理得到两柱之间最优值b[][] for(int ...