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

java springboot与redis整合

2017-08-10 10:41 701 查看
今天我们来演示一下如何将redis整合到springboot中,其实与其说整合,不如说是直接使用。因为我们强大的springboot已经将redis帮我们整合好了。我们只需要按照springboot的要求将配置写到properties配置文件中即可,十分方便。但是方便的同时也会出现一些问题,今天我们就来演示如何使用springboot整合的redis以及会遇到的一些问题和解决方案。

首先我们要使用redis自然就需要有一个redis环境,至于如何搭建一个redis环境,同学们可以从这篇文章中查看 Linux下进行Redis安装以及一些redis配置 这里我就不过多赘述。

环境搭建

我们还是基于之前我们搭建好的多module项目进行redis的添加和整合,具体搭建过程可查看此篇文章 java 基于springboot使用ssh(spring + springmvc + hibernate)分库配置多数据源方式

添加redis

首先我们来创建一个新的module,专门来配置redis,因为我们可能有许多module都需要使用redis,如果将每个需要使用redis的模块都进行redis的配置的话很是麻烦,而且会有很多的冗余代码,不易读且不美观。所以我们将redis单独创建成一个module,让使用它的module对它进行依赖,具体过程如下

创建redis模块

首先我们创建一个module,并将其更改成springboot模式。创建后的目录结构如下



其中因为springboot已经将redis整合好,所以我们只要在application-redis.properties中根据springboot官方文档的要求给key赋值即可。

添加gradle依赖

compile("org.springframework.boot:spring-boot-starter-data-redis")




redis key

# REDIS (RedisProperties)
spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster.
spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from.
spring.redis.database=0 # Database index used by the connection factory.
spring.redis.url= # Connection URL, will override host, port and password (user will be ignored), e.g. redis://user:password@example.com:6379
spring.redis.host=localhost # Redis server host.
spring.redis.jedis.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.jedis.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.jedis.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.jedis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.lettuce.pool.max-active=8 # Max number of connections that can be allocated by the pool at a given time. Use a negative value for no limit.
spring.redis.lettuce.pool.max-idle=8 # Max number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections.
spring.redis.lettuce.pool.max-wait=-1 # Maximum amount of time (in milliseconds) a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely.
spring.redis.lettuce.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive.
spring.redis.lettuce.shutdown-timeout=100 # Shutdown timeout in milliseconds.
spring.redis.password= # Login password of the redis server.
spring.redis.port=6379 # Redis server port.
spring.redis.sentinel.master= # Name of Redis server.
spring.redis.sentinel.nodes= # Comma-separated list of host:port pairs.
spring.redis.ssl=false # Enable SSL support.
spring.redis.timeout=0 # Connection timeout in milliseconds.


这里我们区我们所需要的key进行配置

application-redis.properties

spring.redis.host=192.168.14.129
spring.redis.port=6379


LoadRedisProperties(读取配置文件用)

package com.beyondli.redis.config;

import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
* Created by beyondLi on 2017/8/8.
*/
@PropertySource(value = "application-redis.properties")
@Component
public class LoadRedisProperties {
}


我可以很负责的说,redis已经配置完了。是不是觉得很不可思议,而且十分简单方便。接下来我们来演示一下如何使用以及其中会存在的一些问题。

使用redis

首先我们先导入RedisTemplate

@Autowired
RedisTemplate redisTemplate;

@RequestMapping(value = "/setRedisInfo")
public void setRedisInfo() {
Teacher teacher = new Teacher();
teacher.setId(1);
teacher.setAge(16);
teacher.setName("s");
redisTemplate.opsForValue().set("1", teacher.toString());
}

@RequestMapping(value = "/getRedisInfo")
public String getRedisInfo() {
String teacher = (String) redisTemplate.opsForValue().get("1");
System.out.println(teacher);
return teacher;
}


测试结果显示如下





看上去并没有什么问题,而且一切正常,数据也存入到redis中了,并且也可以正常的取出。但是我们现在看一下我们的redis中的key值。



这可是个大问题,我们存的key是1呀,怎么是这个东西? 虽然并没有影响我们代码中的存和取,但是我们这给我们开发的时候可是带来了很大的不方便,我要从linux中查看某个key的值根本没办法查看了。造成这种情况的原因是因为springboot自带的redis中的key的默认序列化规则所导致的。 而且使用默认的设置当我们set时存入的value值只能是字符串,如果存入对象也会报错,现在我们就来解决这个问题,来为redis设置我们所需要的序列化规则,让它存入到linux的redis中的key不会乱码,并且我们可以将对象存入到值中并将其取出。

配置redis序列化规则



增加RedisCacheConfig配置

package com.beyondli.redis.config;

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.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.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
@EnableCaching //启用缓存
public class RedisCacheConfig  {
@Bean
public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate) {

CacheManager cacheManager = new RedisCacheManager(redisTemplate);

return cacheManager;

}

@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {

RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
RedisSerializer<String> redisSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(redisSerializer);
redisTemplate.setHashKeySerializer(redisSerializer);
redisTemplate.setValueSerializer(redisSerializer);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);

redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();

return redisTemplate;
}
}


测试代码

@RequestMapping(value = "/setRedisInfo")
public void setRedisInfo() {
Teacher teacher = new Teacher();
teacher.setId(1);
teacher.setAge(16);
teacher.setName("s");
redisTemplate.opsForValue().set("1", teacher);
}

@RequestMapping(value = "/getRedisInfo")
public Teacher getRedisInfo() {
Teacher teacher = (Teacher) redisTemplate.opsForValue().get("1");
System.out.println(teacher);
return teacher;
}


测试结果







好了 这次一切正常了。我们的redis能正常的存取数据,并且linux中redis的值也可以正常显示并且进行查看了。

项目代码:链接:http://pan.baidu.com/s/1mhCWZiC 密码:wc87

以上观点均属本人个人理解,如有错误或不足,望指出,共同成长。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: