
spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化。
redis介绍
Redis是目前业界使用最广泛的内存数据存储。相比memcached,Redis支持更丰富的数据结构,例如hashes, lists,
sets等,同时支持数据持久化。除此之外,Redis还提供一些类数据库的特性,比如事务,HA,主从库。可以说Redis兼具了缓存系统和数据库的一些特性,因此有着丰富的应用场景。本文介绍Redis在Spring
Boot中两个典型的应用场景。
如何使用
1、引入 spring-boot-starter-redis
<dependency>
<groupId>orgspringframeworkboot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
2、添加配置文件
# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
springredisdatabase=0
# Redis服务器地址
springredishost=192168058
# Redis服务器连接端口
springredisport=6379
# Redis服务器连接密码(默认为空)
springredispassword=
# 连接池最大连接数(使用负值表示没有限制)
springredispoolmax-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
springredispoolmax-wait=-1
# 连接池中的最大空闲连接
springredispoolmax-idle=8
# 连接池中的最小空闲连接
springredispoolmin-idle=0
# 连接超时时间(毫秒)
springredistimeout=0
3、添加cache的配置类
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport{
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object params) {
StringBuilder sb = new StringBuilder();
sbappend(targetgetClass()getName());
sbappend(methodgetName());
for (Object obj : params) {
sbappend(objtoString());
}
return sbtoString();
}
};
}
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
//rcmsetDefaultExpiration(60);//秒
return rcm;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Objectclass);
ObjectMapper om = new ObjectMapper();
omsetVisibility(PropertyAccessorALL, JsonAutoDetectVisibilityANY);
omenableDefaultTyping(ObjectMapperDefaultTypingNON_FINAL);
jackson2JsonRedisSerializersetObjectMapper(om);
templatesetValueSerializer(jackson2JsonRedisSerializer);
templateafterPropertiesSet();
return template;
}
}
3、好了,接下来就可以直接使用了
@RunWith(SpringJUnit4ClassRunnerclass)
@SpringApplicationConfiguration(Applicationclass)
public class TestRedis {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate redisTemplate;
@Test
public void test() throws Exception {
stringRedisTemplateopsForValue()set("aaa", "111");
AssertassertEquals("111", stringRedisTemplateopsForValue()get("aaa"));
}
@Test
public void testObj() throws Exception {
User user=new User("aa@126com", "aa", "aa123456", "aa","123");
ValueOperations<String, User> operations=redisTemplateopsForValue();
operationsset("comneox", user);
operationsset("comneof", user,1,TimeUnitSECONDS);
Threadsleep(1000);
//redisTemplatedelete("comneof");
boolean exists=redisTemplatehasKey("comneof");
if(exists){
Systemoutprintln("exists is true");
}else{
Systemoutprintln("exists is false");
}
// AssertassertEquals("aa", operationsget("comneof")getUserName());
}
}
以上都是手动使用的方式,如何在查找数据库的时候自动使用缓存呢,看下面;
4、自动根据方法生成缓存
@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
User user=userRepositoryfindByUserName("aa");
Systemoutprintln("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return user;
}
其中value的值就是缓存到redis中的key
Spring Boot是目前非常流行的Java Web开发框架,Redis是非关系型数据库的一种,以键值对的形式存储。Spring对Redis的支持是通过Spring Data Redis来实现的,给我们提供了RedisTemplate和StringRedisTemplate两种模板来 *** 作数据。Spring Boot框架也提供了对Redis的支持,下面我们来讲一下Spring Boot框架整合Redis的步骤。
工具/材料IntelliJ IDEA
Spring Boot整合Redis我们需要添加依赖的jar包,spring-boot-starter-data-redis中包含spring和redis相关的jar包,jedis作为redis的客户端也需要添加到工程中,Spring Boot的版本信息在父pom中已指定,子模块中的spring相关的jar包无需另外指定。<dependency>
<groupId>orgspringframeworkboot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redisclients</groupId>
<artifactId>jedis</artifactId>
<version>300-m1</version>
</dependency>
Spring Boot会根据applicationproperties中的配置对Redis的属性进行自动配置,并注入到RedisProperties类中。在applicationproperties配置文件中这些属性都是以springredis为前缀的,值得注意的是在Spring Boot 15x版本中默认的Redis客户端是jedis,因此在配置文件中无需指定,如下图所示。
Spring Boot 15x版本的整合配置网上可以搜索大量的文章,然而Spring Boot 2x版本的整合资料却非常少,甚至提供的配置不能正常使用,因此本文主要讲解Spring Boot 2x整合Redis以及Redis的使用情况。spring-boot 2x版本有jedis和lettuce两种客户端,因此我们必须要去指定使用哪一种客户端,两个客户端的配置如下图所示,本文使用的是Jedis客户端连接池,具体的配置如下。
# Redis数据库索引(默认为0)
springredisdatabase=0
# Redis服务器地址
springredishost=127001
# Redis服务器连接端口
springredisport=6379
# Redis服务器连接密码(默认为空)
springredispassword=xylx1t!@#
# 配置jedis连接池
# 连接池最大连接数(使用负值表示没有限制)
springredisjedispoolmax-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
springredisjedispoolmax-wait=-1ms
# 连接池中的最大空闲连接
springredisjedispoolmax-idle=8
# 连接池中的最小空闲连接
springredisjedispoolmin-idle=0
# 连接超时时间(毫秒)
springredistimeout=5000ms
由配置我们可以看到spring-boot 2x版本时间设置需要加单位ms,因为参数的类型为Duration。另外springredistimeout尽量不要配置0,否则可能会出现iolettucecoreRedisCommandTimeoutException: Command timed out超时错误。
配置文件编辑完成后,我们开始编写代码实现Redis数据的存储和读取。我们创建一个RedisUtil工具类,该类使用@Component注解表示交由Spring管理,StringRedisTemplate是Spring提供的,可以使用@Autowired注解直接注入,接下来便可以书写存和取的代码了。@Component
public class RedisUtil {
@Autowired
private StringRedisTemplate redisTemplate;
/
存字符串
@param key 缓存键
@param value 缓存值
@param expireTime过期时间(s)
/
public void setString(String key, String value, int expireTime){
ValueOperations<String, String> ops = redisTemplateopsForValue();
if (expireTime != 0) {
opsset(key, value, expireTime, TimeUnitSECONDS);
} else {
opsset(key,value);
}
}
/
取字符串
@param key 缓存键
@return缓存值
/
public String getString(String key){
ValueOperations<String, String> ops = thisredisTemplateopsForValue();
return opsget(key);
}
接下来我们编写Controller层代码去调用RedisUtil工具类,实现数据的存储和读取,代码比较简单可以参考下图。若想验证Redis是否可用,还需要编写启动类,如下图所示。
由上图可看到我们编写了一个post请求用于存储字符串,get请求用于取出字符串。启动类通过main方法启动应用,接下来我们使用postman去模拟浏览器调用post和get请求,由下图可以看到Redis存储的数据成功被取出。
接下来我们介绍Jedis,这是一个封装了Redis的客户端,在Spring Boot整合Redis的基础上,可以提供更简单的API *** 作。因此我们需要配置JedisPool的Bean,代码如下,其中@Configuration注解表明这是一个配置类,我们在该类中注入RedisProperties,并且使用@Bean注解指定JedisPool。
@Configuration
public class RedisConfiguration {
@Autowired
private RedisProperties properties;
@Bean
public JedisPool getJedisPool(){
JedisPoolConfig config = new JedisPoolConfig();
configsetMaxIdle(propertiesgetJedis()getPool()getMaxIdle());
configsetMaxTotal(propertiesgetJedis()getPool()getMaxActive());
configsetMaxWaitMillis(propertiesgetJedis()getPool()getMaxWait()toMillis());
JedisPool pool = new JedisPool(config,propertiesgetHost(),
propertiesgetPort(),100,
propertiesgetPassword(), propertiesgetDatabase());
return pool;
}
}
接下来我们编辑JedisUtil工具类,通过SpringBoot容器的@Component注解来自动创建,并且注入JedisPool,使用jedisPoolgetResource()方法来获取Jedis,并最终实现 *** 作redis数据库,其代码如下。@Component
public class JedisUtil {
@Autowired
JedisPool jedisPool;
//获取key的value值
public String get(String key) {
Jedis jedis = jedisPoolgetResource();
String str = "";
try {
str = jedisget(key);
} finally {
try {
jedisclose();
} catch (Exception e) {
eprintStackTrace();
}
}
return str;
}
public String set(String key, String value) {
Jedis jedis = jedisPoolgetResource();
String str = "";
try {
str = jedisset(key, value);
} finally {
try {
jedisclose();
} catch (Exception e) {
eprintStackTrace();
}
}
return str;
}
}
JedisUtil工具类编写完成后,我们修改之前的RedisController,并注入JedisUtil,代码如下图所示。然后再用postman分别调用post和get接口,我们可以看到成功取到了新的key的value值。
特别提示在Spring Boot整合Redis前本机需安装Redis,另外可以使用RedisDesktopManager这个Redis这个桌面管理工具查看Redis中的数据。
redis 是线程安全
Redis是一个开源,先进的key-value存储,并用于构建高性能,可扩展的Web应用程序的完美解决方案,是线程安全的。
Redis三个主要特点:
Redis数据库完全在内存中,使用磁盘仅用于持久性。
相比许多键值数据存储,Redis拥有一套较为丰富的数据类型。
Redis可以将数据复制到任意数量的从服务器。
以上就是关于怎么看spring-bootspring-data-redis全部的内容,包括:怎么看spring-bootspring-data-redis、Spring Boot如何整合Redis、redistemplate valueoperations线程安全吗等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)