版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Calvin_1016280226/article/details/79807208
Redis
一、What is Redis ?
**Redis 是一个分布式高性能内存(key-value)数据库。**
二、Redis Effect ?
1.内存存储和持久化
2.可以将热搜关键字词放入到缓存中
3.可以设定时间清除缓存
4.支持订阅发布消息
5.支持定时器、计数器
三、Redis main content:
1.Redis Persistence (持久化)
RDB
AOF
2.Redis Transaction(事务)
正常事务
放弃事务
全体出错
冤头债主
watch 监控
3.Redis Replication(主从复制)
一主二仆
薪火相传
反客为主
哨兵模式
四、Redis + SpringBoot 集成
1.添加 Redis 依赖 + 添加 SpringBoot 依赖 + 测试组件 + lombok插件
<dependencies>
<!--springboot 启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>${springboot.version}</version>
</dependency>
<!--springboot web 启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>${springboot.version}</version>
</dependency>
<!--springboot springdata redis 启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>${springboot.version}</version>
</dependency>
<!--springboot session redis-->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
<version>${springboot-session-data-redis.version}</version>
</dependency>
<!--springboot 测试组件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>1.4.3.RELEASE</version>
<scope>test</scope>
</dependency>
<!--spring 测试组件-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
2.创建一个相关的Redis配置,为了放入到spirng 容器中,名为:RedisCacheAutoConfiguration.java
package org.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import java.lang.reflect.Method;
/**
* Created by Calvin on 2018/3/30
* Redis 缓存配置类
*/
@Configuration
/**
* @EnableScheduling 开启计划任务支持
*/
@EnableScheduling
/**
* 开启驱动缓存(启用 spring 对注解驱动缓存的支持 )
*/
@EnableCaching
/**
* @EnableRedisHttpSession 开启redis集中式session管理,所有的session都存放到了redis中
* @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) maxInactiveIntervalInSeconds来设定session的统一过期时间
*/
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)
public class RedisCacheAutoConfiguration extends CachingConfigurerSupport{
/**
* 默认键值生成器:类名+方法名+参数
* Cacheable中设置 key="xx"后按此生成
* @return
*/
@Override
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
public Object generate(Object o, Method method, Object... objects) {
StringBuilder sb = new StringBuilder();
sb.append(method.getClass().getName());
sb.append(method.getName());
for (Object obj : objects) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
//==========================================================将CacheManager 声明为Bean ===============================================
/**
* 缓存管理器
* 作用:它是spring 缓存抽象核心,它能够与多个流行的缓存实现进行集成
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate){
// 序列化String 类型的key 和 Value
RedisSerializer redisSerializer = new StringRedisSerializer();
//设置此模板所使用的Key序列化器
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setHashKeySerializer(redisSerializer);
// 将redisTemplate 放入到缓存管理器中
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
// 设置缓存过期时间: 秒
redisCacheManager.setDefaultExpiration(60*30);
return redisCacheManager;
}
//==========================================================将RedisTemplate 声明为Bean ===============================================
/**
* @suppressWarnings 让IDE 不报: Could not autowire
* @param redisConnectionFactory
* @return
*/
@SuppressWarnings("SpringJavaAutowiringInspection")
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
// Redis 数据访问
StringRedisTemplate redisTemplate = new StringRedisTemplate(redisConnectionFactory);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// 序列化Redis的key(键)
redisTemplate.setKeySerializer(stringRedisSerializer);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
// 使用ObjectMapper 来进行java 对象的相互转换
ObjectMapper om = new ObjectMapper();
/**
* PropertyAccessor(属性访问器) JsonAutoDetect(自动检测)
* setVisibility 设置可见性
* om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 设置可见性为:所有属性可以访问和任何级别的字段都可以自动识别
*/
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 启用默认类型为:不带final 类型
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 序列化Redis的value(值)
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
//afterPropertiesSet 加载配置后执行
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
3.编写Redis相关的接口。
CommandsService
AOFService
RDBService
RedisTransaction
RedisTypes
4.配置Redis相关配置在spring boot的配置下applicaiton.properties/applicaiton-dev.yml
####**application-dev.yml
** spring: redis: database: 15 # Redis数据库索引(默认为0~15) host: 192.168.50.151 # Redis服务器地址 port: 6380 # Redis服务器连接密码(默认为空) pool: # 连接池 max-active: 300 # 连接池最大连接数(使用负值表示没有限制) max-wait: 1000 # 连接池最大阻塞等待时间(使用负值表示没有限制) max-idle: 100 # 连接池中的最大空闲连接 min-idle: 0 # 连接池中的最小空闲连接 timeout: 0 # 连接超时时间(毫秒)
####**application.properties
**
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=192.168.0.58
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
5.编写测试类
RedisConnectionTest.java
import org.junit.Test;
import org.junit.runner.RunWith;
import org.redis.RedisStaterApplication;
import org.redis.command.CommandsService;
import org.redis.types.RedisTypes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* Created by Calvin on 2018/4/2
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = RedisStaterApplication.class)
public class RedisConnectionTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private CommandsService commandsService;
@Autowired
private RedisTypes redisTypes;
@Test
public void test() throws Exception{
redisTypes.set("k2", "v2");
}
}