一、简介
SpringBoot自从问世以来,以其方便的配置受到了广大开发者的青睐。它提供了各种starter简化很多繁琐的配置。SpringBoot整合Druid、Mybatis已经司空见惯,在这里就不详细介绍了。今天我们要介绍的是使用SpringBoot整合Redis、ApacheSolr和SpringSession。
二、SpringBoot整合Redis
Redis是大家比较常用的缓存之一,一般Redis都会搭建高可用(HA),Cluster或者Sentinel。具体的搭建方法请参照Redis官方文档。我们这里已Sentinel举例,搭建RedisSentinel一般都是3个节点,Redis的端口一般是6379,Sentinel的端口一般是26379。
我们要使用SpringBoot整合Redis,首先要把对应的Redis的starter加入到POM中:

引入jar包以后,我们直接在application.properties文件中,添加RedisSentinel的配置即可完成整合。

sentinel.master是master的名称,我们搭建RedisSentinel时使用的默认的名称mymaster。
sentinel.nodes是sentinel的节点,注意是sentinel的节点,不是redis的节点。用ip:端口的格式,多个节点用“,”隔开。
下面则是一些连接池的信息:
- pool.max-active:最大活跃数
- pool.max-idle:最大空闲数
- pool.min-idle:最小空闲数
- pool.max-wait:最大等待时间
在程序中,我们可以直接注入redisTemplate,对Redis进行操作

至此,Redis整合完了。
三、SpringBoot整合SpringSession
SpringSession提供了集群Session的管理,无需通过容器。它可以接入不同的存储层,例如:数据库、Redis、MongoDB等。它可以和SpringBoot无缝结合。
首先,我们将SpringSession引入到项目中,在POM中加入如下配置:

然后在application.properties中指定一下SpringSession的存储类型:

这样就非常简单的整合了SpringSession,如果对cookie有特别的要求,可以在项目中新建cookie的Bean来代替SpringBoot自动创建的bean。具体如下:

上述的例子,我们修改了cookie的名字。如需修改其他属性,请set相关的属性值。
四、SpringBoot整合Solr
ApacheSolr是比较常见的搜索引擎,SpringBoot也可以非常方便的整合solr,方便大家的开发。具体的ApacheSolr的概念以及用法请自行查阅相关文档。在搭建solr时,我们一般都会借助zookeeper来搭建SolrCloud,以提高Solr的可用性。在这里我们整理SolrCloud。
首先我们引入ApacheSolr的starter:

在application.properties中,添加zookeeper的信息,如下:

多个zookeeper时,用“,”隔开。
这样,SpringBoot整合ApacheSolr就完成了,非常方便吧。接下来我们就可以用Spring-data来访问solr了。
1、编写自己的实体类对应solr返回的数据,具体代码如下:

@Setter@Getter这两个注解大家比较常见,用于生成get、set方法。
@SolrDocument(solrCoreName = "xy_company"),用于指定这个实体对应solr中的core或collection,core是单实例中的称呼,collection是SolrCloud中的称呼,意思大体一样。
@Field("id"),用于指定对应solr中的字段。
2、编写自己的存储层,继承SolrCrudRepository,如下:

这样,这个存储层就可以访问solr了,如果多个存储层共用一个实体,可以写多个存储层,继承不同Repository,具体请查阅Spring-data。
3、在自己的业务中,使用solr

至此,SpringBoot整合Solr就完成了,很简单吧。
本文作者:小忽悠
本文为云栖社区原创内容,未经允许不得转载。
网友评论