前言

到目前为止,把项目中需要用到的:properties读取、数据源配置、整合mybatis/JdbcTemplate、AOP、WebService、redis、filter、interceptor、定时器等,都简单的去用spring boot整合学习了一下。与学习之初对spring boot的理解并没有什么大的区别,只是大致知道怎么配置/注入想要的。

一、准备

1.1 redis服务端的下载及安装

官网:https://redis.io/

1.2 redis需要的jar
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>

1.3 redis的应用场景

自己知道理解的就2个场景:1、缓存; 2、构建消息队列。 (参考:Redis作者谈Redis应用场景)

二、demo

2.1 redis的可用配置
# REDIS (RedisProperties)
spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from.
spring.redis.database=0 # Database index used by the connection factory.
spring.redis.url= # Connection URL, will override host, port and password (user will be ignored), e.g. redis://user:password@example.com:6379
spring.redis.host=localhost # Redis server host.
spring.redis.password= # Login password of the redis server.
spring.redis.ssl=false # Enable SSL support.
spring.redis.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.port=6379 # Redis server port.
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis.timeout=0 # Connection timeout in milliseconds.
2.2 StringRedisTemplate的注入

与JdbcTemplate一样,在spring boot中注入StringRedisTemplate是相当简单的事。这也是使用redis的核心之一。

如果,不指定配置RedisConnectionFactory,默认情况下将尝试使用localhost:6379连接Redis服务器。

@SpringBootApplication
@EnableCaching //允许缓存 (此demo允许redis缓存)
public class RedisApplication {
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
} public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
}

2,3 controller模拟

@Controller
public class RedisController {
private static final String STR_REDIS_KEY = "vergil"; @Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private RedisCacheDao cacheDao; @GetMapping("/redis")
public String index() {
return "redis/redis_index";
} @PostMapping("/setString")
@ResponseBody
public Map<String, Object> setString(String value) {
redisTemplate.opsForValue().set(STR_REDIS_KEY, value);
Map<String, Object> map = new HashMap<String, Object>();
map.put("msg", "ok");
return map;
} @PostMapping("/getString")
@ResponseBody
public Map<String, Object> getString() {
String value = redisTemplate.opsForValue().get(STR_REDIS_KEY);
Map<String, Object> map = new HashMap<String, Object>();
map.put("value", value);
map.put("msg", "ok");
return map;
} @PostMapping("/getCache")
@ResponseBody
public RedisCacheBean get(@RequestParam String id) {
return cacheDao.get(id);
}
}

2.4 view页面效果

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="./static/common/jquery-2.1.4.js"></script>
<title>spring boot redis</title>
<script type="text/javascript"> /*<![CDATA[*/
function setString() {
$.ajax({
type : 'POST',
url : '/setString',
data : {"value":$("#value").val()},
success : function(r) {
alert(r.msg);
},
error : function() {
alert('error!')
}
});
} function getString() {
$.ajax({
type : 'POST',
contentType : 'application/json',
url : '/getString',
success : function(r) {
alert(r.msg);
$("#result").text(JSON.stringify(r));
},
error : function() {
alert('error!')
}
});
}
function getCache() {
$.ajax({
type : 'POST',
contentType : 'application/json',
url : '/getCache?id='+$("#cacheId").val(),
success : function(r) {
$("#cacheResult").text(JSON.stringify(r));
},
error : function() {
alert('error!')
}
});
}
/*]]>*/
</script>
</head>
<body>
<h4>base redis</h4>
<input type="text" id="value" />
<input type="button" value="设置" onclick="setString()" /><br/>
<input type="button" value="获取" onclick="getString()" /><br/>
<h5>结果:</h5>
<p id="result"></p>
<br /> <h4>redis cache</h4>
<input type="text" id="cacheId" /><br/>
<input type="button" value="获取缓存" onclick="getCache()" /><br/>
<h5>缓存结果:</h5>
<p id="cacheResult"></p>
</body>
</html>

效果:

1、当点击"设置",把输入值保存到redis缓存。

2、当点击"获取",从redis中获取到1中设置的值。

(简单理解就是java中的map)

2.5 redis开启缓存模式

1、如果是缓存模式,那么必须在*Application中加入注解:@EnableCaching。

2、@Cacheable注解可以用在方法或者类级别。当他应用于方法级别的时候,就是如上所说的缓存返回值。当应用在类级别的时候,这个类的所有方法的返回值都将被缓存。

(注:@Cacheable是spring提供的,并不是redis。详细用处及细节可另看。)

@Repository
public class RedisCacheDao { /**
* 模拟从数据库获取的数据
*/
@Cacheable(value = "redisCacheBean", key = "'.id.'+#id")
public RedisCacheBean get(String id) {
RedisCacheBean redisCacheBean = new RedisCacheBean(id, "name_"+id, new Date(), id.length() * 10);
return redisCacheBean;
}
}

public class RedisCacheBean implements Serializable{
private static final long serialVersionUID = 1L;
public String id;
public String name;
public String date;
public int quantity; public RedisCacheBean(String id, String name, Date date, int quantity) {
super();
this.id = id;
this.name = name;
this.date = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss").format(date);
this.quantity = quantity;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
} }

RedisCacheBean.java

三、题外话

简单整合redis就这么点东西,没任何别的有深度的东西。所以spring boot的“约定优于配置”,简化了相当多的项目构建。

另外,不光redis包括其他的java开源jar。如果你只是写一个demo,写一个“Hello World”真的不要太简单。就像用excel一样,上手会用很简单,但真要精通灵活相当之复杂。

所以,如果有毅力、兴趣、时间,还是应该深入看一下,不要只在表面用、写业务逻辑代码。看看那些好的jar是怎么实现的。

(其实最近都是强迫自己写博客,但写完一看没任何东西,无奈...各种烦心事...)

【spring boot】SpringBoot初学(8)– 简单整合redis的更多相关文章

  1. Spring Boot(十三):整合Redis哨兵,集群模式实践

    前面的两篇文章(Redis的持久化方案, 一文掌握Redis的三种集群方案)分别介绍了Redis的持久化与集群方案 -- 包括主从复制模式.哨兵模式.Cluster模式,其中主从复制模式由于不能自动做 ...

  2. SpringBoot简单整合redis

    Jedis和Lettuce Lettuce 和 Jedis 的定位都是Redis的client,所以他们当然可以直接连接redis server. Jedis在实现上是直接连接的redis serve ...

  3. Spring Boot 2.x 综合示例-整合thymeleaf、mybatis、shiro、logging、cache开发一个文章发布管理系统

    一.概述 经过HelloWorld示例(Spring Boot 2.x 快速入门(上)HelloWorld示例)( Spring Boot 2.x 快速入门(下)HelloWorld示例详解)两篇的学 ...

  4. Spring Boot 2.0 快速集成整合消息中间件 Kafka

    欢迎关注个人微信公众号: 小哈学Java, 每日推送 Java 领域干货文章,关注即免费无套路附送 100G 海量学习.面试资源哟!! 个人网站: https://www.exception.site ...

  5. spring boot: @Entity @Repository一个简单的数据读存储读取

    spring boot: @Entity @Repository一个简单的数据读存储读取 创建了一个实体类. 如何持久化呢?1.使用@Entity进行实体类的持久化操作,当JPA检测到我们的实体类当中 ...

  6. 实例讲解Springboot以Template方式整合Redis及序列化问题

    1 简介 之前讲过如何通过Docker安装Redis,也讲了Springboot以Repository方式整合Redis,建议阅读后再看本文效果更佳: (1) Docker安装Redis并介绍漂亮的可 ...

  7. 解决Spring Boot(2.1.3.RELEASE)整合spring-data-elasticsearch3.1.5.RELEASE报NoNodeAvailableException[None of the configured nodes are available

    Spring Boot(2.1.3.RELEASE)整合spring-data-elasticsearch3.1.5.RELEASE报NoNodeAvailableException[None of ...

  8. Spring Boot 支持 HTTPS 如此简单,So easy!

    这里讲的是 Spring Boot 内嵌式 Server 打 jar 包运行的方式,打 WAR 包部署的就不存在要 Spring Boot 支持 HTTPS 了,需要去外部对应的 Server 配置. ...

  9. Spring Boot 支持 HTTPS 如此简单,So easy!

    这里讲的是 Spring Boot 内嵌式 Server 打 jar 包运行的方式,打 WAR 包部署的就不存在要 Spring Boot 支持 HTTPS 了,需要去外部对应的 Server 配置. ...

随机推荐

  1. 10个很多人不知道的Redis使用技巧

    前言 Redis 在当前的技术社区里是非常热门的.从来自 Antirez 一个小小的个人项目到成为内存数据存储行业的标准,Redis已经走过了很长的一段路.随之而来的一系列最佳实践,使得大多数人可以正 ...

  2. 在Anaconda3下安装(CPU版)TensorFlow(清华镜像源)

    1.打开Anaconda Prompt 2.搭建TensorFlow的环境: conda config --add channels https://mirrors.tuna.tsinghua.edu ...

  3. java编写杨辉三角

    import java.util.Scanner; /* *计算杨辉三角: * 规律:两边都是1 * 从第三行开始,上一行的前一个元素+与其并排的元素等于下面的元素 * 例如: * 1 * 11 * ...

  4. python如何从内存地址上加载pythn对象

    python如何从内存地址上加载pythn对象 在python中我们可以通过id函数来获取某个python对象的内存地址,或者可以通过调用对象的__repr__魔术函数来获取对象的详细信息 def t ...

  5. OpenCV3入门1—环境搭建与实验

    1.环境搭建 1.1 VS2017开发环境搭建 1).下载软件包 https://opencv.org/ 2).配置环境变量 配置win10系统环境变量,把下面路径添加到path. D:\WORK\5 ...

  6. C++ 自动类型推断

    C++语言提供了自动类型推断的机制,用于简化代码书写,这是一种很不错的特性,使用auto和decltype都可以完成自动类型推断的工作,而且都工作在编译期,这表示在运行时不会有任何的性能损耗. 一.a ...

  7. ICC中对Skew进行Debug的好工具--Interactive CTS Window

    本文转自:自己的微信公众号<集成电路设计及EDA教程> ​以后打算交替着推送多种EDA工具的教程而不只是单纯针对某个工具,依次来满足不同粉丝的需求. 这里分享一篇多年之前写的推文,虽然时间 ...

  8. 🔥SpringBoot图文教程2—日志的使用「logback」「log4j」

    有天上飞的概念,就要有落地的实现 概念+代码实现是本文的特点,教程将涵盖完整的图文教程,代码案例 文章结尾配套自测面试题,学完技术自我测试更扎实 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例 ...

  9. xgboost load model from demp text file

    python package : https://github.com/mwburke/xgboost-python-deploy import xgboost as xgb import numpy ...

  10. HDU_1176_DP

    http://acm.hdu.edu.cn/showproblem.php?pid=1176 简单dp,转换后跟上一题数塔一样,注意每秒只能移动一格,还有在边缘的情况. #include<ios ...