spring boot对常用的数据库支持外,对nosql 数据库也进行了封装自动化。

redis介绍

Redis是目前业界使用最广泛的内存数据存储。相比memcached,Redis支持更丰富的数据结构,例如hashes, lists, sets等,同时支持数据持久化。除此之外,Redis还提供一些类数据库的特性,比如事务,HA,主从库。可以说Redis兼具了缓存系统和数据库的一些特性,因此有着丰富的应用场景。本文介绍Redis在Spring Boot中两个典型的应用场景。

如何使用

1、引入 spring-boot-starter-redis

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

2、添加配置文件

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=
# Redis服务器地址
spring.redis.host=192.168.0.58
# Redis服务器连接端口
spring.redis.port=
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=
# 连接超时时间(毫秒)
spring.redis.timeout=

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();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
} @SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
//rcm.setDefaultExpiration(60);//秒
return rcm;
} @Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
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);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
} }

3、好了,接下来就可以直接使用了

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class TestRedis { @Autowired
private StringRedisTemplate stringRedisTemplate; @Autowired
private RedisTemplate redisTemplate; @Test
public void test() throws Exception {
stringRedisTemplate.opsForValue().set("aaa", "");
Assert.assertEquals("", stringRedisTemplate.opsForValue().get("aaa"));
} @Test
public void testObj() throws Exception {
User user=new User("aa@126.com", "aa", "aa123456", "aa","");
ValueOperations<String, User> operations=redisTemplate.opsForValue();
operations.set("com.neox", user);
operations.set("com.neo.f", user,,TimeUnit.SECONDS);
Thread.sleep();
//redisTemplate.delete("com.neo.f");
boolean exists=redisTemplate.hasKey("com.neo.f");
if(exists){
System.out.println("exists is true");
}else{
System.out.println("exists is false");
}
// Assert.assertEquals("aa", operations.get("com.neo.f").getUserName());
}
}

以上都是手动使用的方式,如何在查找数据库的时候自动使用缓存呢,看下面;

4、自动根据方法生成缓存

@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
User user=userRepository.findByUserName("aa");
System.out.println("若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功");
return user;
}

其中value的值就是缓存到redis中的key

共享Session-spring-session-data-redis

分布式系统中,sessiong共享有很多的解决方案,其中托管到缓存中应该是最常用的方案之一,

Spring Session官方说明

Spring Session provides an API and implementations for managing a user’s session information.

如何使用

1、引入依赖

<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>

2、Session配置:

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = *)
public class SessionConfig {
}

maxInactiveIntervalInSeconds: 设置Session失效时间,使用Redis Session之后,原Boot的server.session.timeout属性不再生效

好了,这样就配置好了,我们来测试一下

3、测试

添加测试方法获取sessionid

@RequestMapping("/uid")
String uid(HttpSession session) {
UUID uid = (UUID) session.getAttribute("uid");
if (uid == null) {
uid = UUID.randomUUID();
}
session.setAttribute("uid", uid);
return session.getId();
}

登录redis 输入 keys '*sessions*'

t<spring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4
t(spring:session:expirations:

其中 1472976480000为失效时间,意思是这个时间后session失效,db031986-8ecc-48d6-b471-b137a3ed6bc4 为sessionId,登录http://localhost:8080/uid 发现会一致,就说明session 已经在redis里面进行有效的管理了。

如何在两台或者多台中共享session

其实就是按照上面的步骤在另一个项目中再次配置一次,启动后自动就进行了session共享。

SpringBoot(三)整合Redis的更多相关文章

  1. SpringBoot简单整合redis

    Jedis和Lettuce Lettuce 和 Jedis 的定位都是Redis的client,所以他们当然可以直接连接redis server. Jedis在实现上是直接连接的redis serve ...

  2. springBoot(8)---整合redis

    Springboot整合redis 步骤讲解 1.第一步jar导入: <dependency> <groupId>org.springframework.boot</gr ...

  3. SpringBoot学习(七)—— springboot快速整合Redis

    目录 Redis缓存 简介 引入redis缓存 代码实战 Redis缓存 @ 简介 redis是一个高性能的key-value数据库 优势 性能强,适合高度的读写操作(读的速度是110000次/s,写 ...

  4. SpringBoot之整合Redis分析和实现-基于Spring Boot2.0.2版本

    背景介绍 公司最近的新项目在进行技术框架升级,基于的Spring Boot的版本是2.0.2,整合Redis数据库.网上基于2.X版本的整个Redis少之又少,中间踩了不少坑,特此把整合过程记录,以供 ...

  5. 【SpringBoot】整合Redis实战

    ========================9.SpringBoot2.x整合Redis实战 ================================ 1.分布式缓存Redis介绍 简介: ...

  6. 完整SpringBoot Cache整合redis缓存(二)

    缓存注解概念 名称 解释 Cache 缓存接口,定义缓存操作.实现有:RedisCache.EhCacheCache.ConcurrentMapCache等 CacheManager 缓存管理器,管理 ...

  7. SpringBoot中整合Redis、Ehcache使用配置切换 并且整合到Shiro中

    在SpringBoot中Shiro缓存使用Redis.Ehcache实现的两种方式实例 SpringBoot 中配置redis作为session 缓存器. 让shiro引用 本文是建立在你是使用这sh ...

  8. SpringBoot之整合Redis

    一.SpringBoot整合单机版Redis 1.在pom.xml文件中加入redis的依赖 <dependency> <groupId>org.springframework ...

  9. springboot下整合redis使用redisTemplate模板

    pom <!-- 引入 redis 依赖 --> <dependency> <groupId>org.springframework.boot</groupI ...

  10. springboot+JPA 整合redis

    1.导入redis依赖: <dependency> <groupId>org.springframework.boot</groupId> <artifact ...

随机推荐

  1. PCB编译时出现的错误 ( Duplicate Net Names Wire N000-1 (Inferred)意思就是端口名字没有定义)

    再运行这个错误Duplicate Net Names Wire N000-1 (Inferred)的就没有了, 不过还有其他的 错误,有错误不用怕,关我的博客解决.

  2. Codeforces Round #513 游记

    Codeforces Round #513 游记 A - Phone Numbers 题目大意: 电话号码是8开头的\(1\)位数字.告诉你\(n(n\le100)\)个数字,每个数字至多使用一次.问 ...

  3. java显示树结构

    /** * 显示多颗树的所有节点的信息 * * @param departmentList */ private void showTreeList(Collection<Department& ...

  4. (华中科大)江南雨烟 C++ STL 专栏

    本文转载来自,华中科技大学江南雨烟的C/C++专栏部分STL剖析文章,以作学习之用. [1]  [C++ STL学习之一]容器的共通能力和共通操作总结 [2]  [C++ STL学习之二]容器vect ...

  5. ie6定位absolute bug触发layout解决

    IE6中很多Bug都可以通过触发layout得到解决,以上的解决方法无论是设置zoom:1还是设置width和height其实都是为了触发layout.下列的CSS属性或取值会让一个元素获得layou ...

  6. C#基于RSA加密算法实现软件注册实战演练

    一.课程介绍 本次分享课程属于<C#高级编程实战技能开发宝典课程系列>中的一部分,阿笨后续会计划将实际项目中的一些比较实用的关于C#高级编程的技巧分享出来给大家进行学习,不断的收集.整理和 ...

  7. 你现在还在手动生成set,get方法吗?使用lombok

    JAVA面向对象编程中的封闭性和安全性.封闭性即对类中的域变量进行封闭操作,即用private来修饰他们,如此一来其他类则不能对该变量访问.这样我们就将这些变量封闭在了类内部,这样就提高了数据的安全性 ...

  8. Java中部分常见语法糖

    语法糖(Syntactic Sugar),也称糖衣语法,指在计算机语言中添加的某种语法,这种语法对语言本身功能来说没有什么影响,只是为了方便程序员的开发,提高开发效率.说白了,语法糖就是对现有语法的一 ...

  9. jconsole工具使用

    Jconsole,Java Monitoring and Management Console. Jconsole是JDK自带的监控工具,在JDK/bin目录下可以找到.它用于连接正在运行的本地或者远 ...

  10. SpringBoot集成Redis分布式锁以及Redis缓存

    https://blog.csdn.net/qq_26525215/article/details/79182687 集成Redis 首先在pom.xml中加入需要的redis依赖和缓存依赖 < ...