本文主要内容:springBoot简介,在SpringBoot中如何集成Redis,可配置Redis集群。java
你想要的,这里都有:https://spring.io/projects/spring-boot 这是SpringBoot的官方文档,开发者已经将你须要的东西都给你了。SpringBoot是一个大的容器,能够在这里很轻松地建立各类Spring应用,而且轻松集成其余框架,能够参照官网的案例完成一个HelloWorld。完成以后你会发现使用SpringBoot是一件多么优雅的事情。node
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
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
你只须要写一个main()方法就能够直接启动你的项目,默认在8080端口启动。比起使用传统的SSM那一套要简单许多,这是由于SpringBoot的设计之禅就是默认优于配置,所以它内置了不少默认的配置,包括Tomcat。可是它并不适合初学者使用。过分的封装致使开发者没法接触底层。git
官网:https://redis.io/redis
基于内存的键值对数据库,能够分布式部署,经常使用做缓存。缺点就是不一样版本之间差别较大。本文中提到的Redis是4.x。spring
操做Redis数据库有一套Jedis JavaAPI。这里使用SpringBoot集成就须要安装它的方式来配置。因为SpringBoot自己集成了许多框架,实质上这里就是使用了Jedis。数据库
首先须要引入maven依赖缓存
groupId: redis.clients artifactId: jedis version: 2.9.0 ------ groupId: org.springframework.data artifactId: spring-data-redis version: 2.0.5.RELEASE
在默认的yml中配置。springboot
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
这里的RedisTemplate就是SpringBoot提供操做Redis的接口类,实际上就是在Jedis基础上的二次封装。mybatis
@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框架