springBoot集成redisCluster

时间:2024-07-31 14:03:56

本文主要内容:springBoot简介,在SpringBoot中如何集成Redis,可配置Redis集群。


关于SpringBoot

你想要的,这里都有:https://spring.io/projects/spring-boot 这是SpringBoot的官方文档,开发者已经将你需要的东西都给你了。SpringBoot是一个大的容器,可以在这里很轻松地创建各种Spring应用,并且轻松集成其他框架,可以参照官网的案例完成一个HelloWorld。完成之后你会发现使用SpringBoot是一件多么优雅的事情。

引入maven依赖

parent
groupId:org.springframework.boot
artifactId:spring-boot-starter-parent
version:2.0.0.RELEASE dependencies
groupId: org.springframework.boot
artifactId: spring-boot-starter build
plugins
plugin
groupId: org.springframework.boot
artifactId: spring-boot-maven-plugin

写一个main()方法

@SpringBootApplication
public class DemoApplication { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

你只需要写一个main()方法就可以直接启动你的项目,默认在8080端口启动。比起使用传统的SSM那一套要简单许多,这是因为SpringBoot的设计之禅就是默认优于配置,因此它内置了很多默认的配置,包括Tomcat。但是它并不适合初学者使用。过度的封装导致开发者无法接触底层。

关于Redis

官网:https://redis.io/

基于内存的键值对数据库,可以分布式部署,常用作缓存。缺点就是不同版本之间差异较大。本文中提到的Redis是4.x。

SpringBoot中集成Redis

操作Redis数据库有一套Jedis JavaAPI。这里使用SpringBoot集成就需要安装它的方式来配置。由于SpringBoot本身集成了许多框架,实质上这里就是使用了Jedis。

引入Maven

首先需要引入maven依赖

groupId: redis.clients
artifactId: jedis
version: 2.9.0
------
groupId: org.springframework.data
artifactId: spring-data-redis
version: 2.0.5.RELEASE

配置Redis

在默认的yml中配置。

spring:
#配置redis
redis:
cluster:
nodes: 192.168.64.120:7000,
192.168.64.120:7001,
192.168.64.120:7002,
192.168.64.120:7003,
192.168.64.120:7004,
192.168.64.120:7005
max-redirects: 3
timeout: 5000
jedis:
pool:
max-active: 10
min-idle: 1
max-wait: -1ms
max-idle: 8

写一个Service提供服务

这里的RedisTemplate就是SpringBoot提供操作Redis的接口类,实际上就是在Jedis基础上的二次封装。

@Service
public class RedisService {
@Autowired
private RedisTemplate redisTemplate; /**
* 写入缓存设置时效时间
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
} /**
* 删除对应的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
...
}

这里只给出了部分代码,全部代码参考:https://gitee.com/Yao_Qi/springboot_integrates_mybatis_and_rediscluster