您的位置:首页 > 数据库 > Redis

Redis---------springboot整合Redis实例

2017-08-04 00:46 686 查看
代码实例:https://github.com/weima123/redis-springboot-demo2.git

之前用SpringBoot+MyBatisPlus+SpringMVC整合搭建了一个基础web开发框架,使用这三个框架搭建出来项目结构非常的清爽,没有过多的配置文件,各个模块之间有清晰的联系,非常适合敏捷开发。

最近学习了Redis这个基于内存的,Key-Value数据形式的高性能数据库,感觉学习了入门之后很简单,没有体会到它具体能干嘛,我就想着使用Redis这个数据库来整合之前搭建的框架,利用Spring中的缓存机制,将查询的信息缓存到Redis中。

、、、、、、、、、、、、
个人博客地址:http://z77z.oschina.io/

,,,,,,,,,,,,

安装Redis

Window 下安装 下载地址:https://github.com/MSOpenTech/redis/releases。 Redis 支持32 位和64 位。这个需要根据你系统平台的实际情况选择,这里我们下载 Redis-x64-xxx.zip压缩包到 C盘的tools目录中,解压后,将文件夹重新命名为 redis。



下载Redis版本

打开一个 cmd 窗口 使用cd命令切换目录到 C:\tools\redis 运行 redis-server.exe redis.windows.conf 。

redis启动指令:1.cd 进入 redis目录下;2.redis-server.exe redis.windows.conf (用redis.windows.conf配置文件启动redis)

redis登录指令
redis-cli.exe -h host -p port -a password


(redis访问默认不需要密码)Redis密码设置
设置密码:config set requirepass(密码)
密码验证:config get requirepass
在redis.windows.conf文件中设置 requirepass 密码

退出redis
shutdown
exit

安装成功后,可以在windows的服务管理中对redis进行管理,就不用每次都打开命令窗口来启动redis服务了,如下图:



在windows中管理redis服务

获取之前项目

环境我就直接在之前的整合框架上进行搭建,之前项目下载地址:https://git.oschina.net/z77z/springboot_mybatisplus

注意:之前搭建这个框架的时候我为了获取基础数据,在启动springboot的时候也启动了爬虫程序,如果不想每次启动都启动爬虫可以注释掉启动类中的run方法。

添加Redis依赖到pom.xml中

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>

springboot配置Redis

1.使用springboot提供的redisConnectionFactory

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# 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


我们需要做的配置到这里就已经完成了,Spring Boot会在侦测到存在Redis的依赖并且Redis的配置是可用的情况下,使用RedisCacheManager初始化CacheManager。也就是说要使用缓存的话,SpringBoot就会选择Redis来作为缓存的容器。


package com.mw.config.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
* Created by mawei on 2017/8/23.
*/
@Configuration
@EnableCaching//启用缓存
@EnableConfigurationProperties(RedisProperties.class)
public class RedisCacheConfig extends CachingConfigurerSupport{

/***
* 缓存管理器
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate){
CacheManager cacheManager = new RedisCacheManager(redisTemplate);
return cacheManager;
}

/**
* redis模板操作类,类似于jdbcTemplate的一个类;
*
* 虽然CacheManager也能获取到Cache对象,但是操作起来没有那么灵活;
*
* 这里在扩展下:RedisTemplate这个类不见得很好操作,我们可以在进行扩展一个我们
*
* 自己的缓存类,比如:RedisStorage类;
*
* @param factory : 通过Spring进行注入,参数在application.properties进行配置;
* @return
*/
@Bean
public RedisTemplate<String ,String> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String,String> redisTemplate = new RedisTemplate<String,String>();
redisTemplate.setConnectionFactory(factory);
//key序列化方式;(不然会出现乱码;),但是如果方法上有Long等非String类型的话,会报类型转换错误;
//所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现ObjectRedisSerializer
//或者JdkSerializationRedisSerializer序列化方式;
//     RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型不可以会出现异常信息;
//     redisTemplate.setKeySerializer(redisSerializer);
//     redisTemplate.setHashKeySerializer(redisSerializer);
return redisTemplate;
}

}


2.使用自己创建的redisConnectionFactory

package com.mw.config.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
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.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
* Created by mawei on 2017/8/23.
*/
@Configuration
@EnableCaching//启用缓存
@EnableConfigurationProperties(RedisProperties.class)
public class RedisCacheConfig extends CachingConfigurerSupport{
@Autowired
private RedisProperties redisProperties;

@Bean(name="redisConnectionFactory")
public JedisConnectionFactory redisConnectionFactory(){
JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();
redisConnectionFactory.setHostName(redisProperties.getHost());
redisConnectionFactory.setPort(redisProperties.getPort());
redisConnectionFactory.setPassword(redisProperties.getPassword());
return redisConnectionFactory;
}
/***
* 缓存管理器
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate){
CacheManager cacheManager = new RedisCacheManager(redisTemplate);
return cacheManager;
}

/**
* redis模板操作类,类似于jdbcTemplate的一个类;
*
* 虽然CacheManager也能获取到Cache对象,但是操作起来没有那么灵活;
*
* 这里在扩展下:RedisTemplate这个类不见得很好操作,我们可以在进行扩展一个我们
*
* 自己的缓存类,比如:RedisStorage类;
*
* @param factory : 通过Spring进行注入,参数在application.properties进行配置;
* @return
*/
@Bean
public RedisTemplate<String ,String> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String,String> redisTemplate = new RedisTemplate<String,String>();
redisTemplate.setConnectionFactory(factory);
//key序列化方式;(不然会出现乱码;),但是如果方法上有Long等非String类型的话,会报类型转换错误;
//所以在没有自己定义key生成策略的时候,以下这个代码建议不要这么写,可以不配置或者自己实现ObjectRedisSerializer
//或者JdkSerializationRedisSerializer序列化方式;
//     RedisSerializer<String> redisSerializer = new StringRedisSerializer();//Long类型不可以会出现异常信息;
//     redisTemplate.setKeySerializer(redisSerializer);
//     redisTemplate.setHashKeySerializer(redisSerializer);
return redisTemplate;
}

}


缓存数据一致性保证

CRUD (Create 创建,Retrieve 读取,Update 更新,Delete 删除) 操作中,除了 R具备幂等性,其他三个发生的时候都可能会造成缓存结果和数据库不一致。为了保证缓存数据的一致性,在进行 CUD 操作的时候我们需要对可能影响到的缓存进行更新或者清除。如下:

/**
* 获取数据,并且做缓存处理
* @author z77z
*
*/
@Component
public class RedisCache {

@Autowired
BeautifulPicturesService beautifulPicturesService;

//查询
@Cacheable(value = "beautifulPictures")
public BeautifulPictures getBeautifulPicturesList(String id) {
return beautifulPicturesService.selectById(id);
}

//修改
@CachePut(value = "beautifulPictures")
public void updateBeautifulPicture(String id) {
BeautifulPictures beautifulPictures = new BeautifulPictures();
beautifulPictures.setTitle("Title被我修改了一下,哈哈");
beautifulPictures.setId(id);
beautifulPicturesService.updateById(beautifulPictures);
}
}

/**
* 测试类
* @author z77z
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
public class RedisCacheTest {
@Autowired
BeautifulPicturesService beautifulPicturesService;

@Autowired
StringRedisTemplate stringRedisTemplate;

@Autowired
RedisCache redisCache;

@Test
public void redisTest() throws Exception {

//保存字符串
stringRedisTemplate.opsForValue().set("aaa", "111");
//读取字符串
String aaa = stringRedisTemplate.opsForValue().get("aaa");
System.out.println(aaa);
}

@Test
public void CacheTest() {
String id = "1";
BeautifulPictures beautifulPicture = redisCache.getBeautifulPicturesList(id);
System.out.println("第一次查询结果:");
System.out.println(beautifulPicture);

BeautifulPictures beautifulPicture1 = redisCache.getBeautifulPicturesList(id);
System.out.println("第二次查询结果:");
System.out.println(beautifulPicture1);

redisCache.updateBeautifulPicture(id);

BeautifulPictures beautifulPicture2 = redisCache.getBeautifulPicturesList(id);
System.out.println("第三次查询结果:");
System.out.println(beautifulPicture2);
}
}

保持缓存一致性测试结果:



保持缓存的一致性测试

在会导致数据发生改变的方法上添加
@CachePut(value = "beautifulPictures")
注解,添加后会更新缓存中的值,并且每次都会正常执行方法内容。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: