网站关键字工具,网站维护 静态页面,wordpress 注册发邮件,国外做旅游攻略的网站Spring boot除了常用的数据库支持外#xff0c;对nosql数据库也进行了封装自动化。
1 Redis介绍 Redis 是目前业界使用最广泛的内存数据存储。相比memcached#xff0c; #xff08;1#xff09;Redis支持更丰富的数据结构#xff0c;例如hashes#xff0c;lists#x…Spring boot除了常用的数据库支持外对nosql数据库也进行了封装自动化。
1 Redis介绍 Redis 是目前业界使用最广泛的内存数据存储。相比memcached 1Redis支持更丰富的数据结构例如hasheslistssets等同时支持数据持久化。 2除此之外Redis还提供一些类数据库的特性比如事务HA主从库。可以说Redis兼具了缓存系统和数据库的一些特性 因此有着丰富的应用场景。介绍两个Redis在Spring boot项目中的典型应用场景。
1.1 如何使用
1 引入spring-boot-starter-redis
dependency groupIdorg.springframework.boot/groupId artifactIdspring-boot-starter-redis/artifactId
/dependency2 添加配置文件
# REDIS (RedisProperties)
# Redis数据库索引默认为0
spring.redis.database0
# Redis服务器地址
spring.redis.host192.168.0.58
# Redis服务器连接端口
spring.redis.port6379
# Redis服务器连接密码默认为空
spring.redis.password
# 连接池最大连接数使用负值表示没有限制
spring.redis.pool.max-active8
# 连接池最大阻塞等待时间使用负值表示没有限制
spring.redis.pool.max-wait-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle0
# 连接超时时间毫秒
spring.redis.timeout03 添加cache的配置类
Configuration
EnableCaching
public class RedisConfig extends CachingConfigurerSupport{Beanpublic KeyGenerator keyGenerator() { return new KeyGenerator() { Overridepublic 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) Beanpublic CacheManager cacheManager(RedisTemplate redisTemplate) {RedisCacheManager rcm new RedisCacheManager(redisTemplate); //设置缓存过期时间//rcm.setDefaultExpiration(60);//秒return rcm;}Beanpublic RedisTemplateString, 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;}}4 好了接下来就可以直接使用了
RunWith(SpringJUnit4ClassRunner.class)
SpringApplicationConfiguration(Application.class)
public class TestRedis { Autowiredprivate StringRedisTemplate stringRedisTemplate;Autowiredprivate RedisTemplate redisTemplate;Testpublic void test() throws Exception {stringRedisTemplate.opsForValue().set(aaa, 111);Assert.assertEquals(111, stringRedisTemplate.opsForValue().get(aaa));} Testpublic void testObj() throws Exception {User usernew User(aa126.com, aa, aa123456, aa,123);ValueOperationsString, User operationsredisTemplate.opsForValue();operations.set(com.neox, user);operations.set(com.neo.f, user,1,TimeUnit.SECONDS);Thread.sleep(1000); //redisTemplate.delete(com.neo.f);boolean existsredisTemplate.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 好了接下来就可以直接使用了
RunWith(SpringJUnit4ClassRunner.class)
SpringApplicationConfiguration(Application.class)
public class TestRedis { Autowiredprivate StringRedisTemplate stringRedisTemplate;Autowiredprivate RedisTemplate redisTemplate;Testpublic void test() throws Exception {stringRedisTemplate.opsForValue().set(aaa, 111);Assert.assertEquals(111, stringRedisTemplate.opsForValue().get(aaa));} Testpublic void testObj() throws Exception {User usernew User(aa126.com, aa, aa123456, aa,123);ValueOperationsString, User operationsredisTemplate.opsForValue();operations.set(com.neox, user);operations.set(com.neo.f, user,1,TimeUnit.SECONDS);Thread.sleep(1000); //redisTemplate.delete(com.neo.f);boolean existsredisTemplate.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(valueuser-key) //Redis获取key的值
public User getUser() {User useruserRepository.findByUserName(aa);System.out.println(若下面没出现“无缓存的时候调用”字样且能打印出数据表示测试成功); return user;
}1.2 共享session-spring-session-data-redis
分布式系统中session共享有很多的解决方案其中托管到缓存中应该是最常用的方案之一。
spring session官方说明
spring session provide an API and implementation for managing a user’s session information.
如何使用
1 引入依赖
dependencygroupIdorg.springframework.session/groupIdartifactIdspring-session-data-redis/artifactId
/dependency2 session配置
Configuration
EnableRedisHttpSession(maxInactiveIntervalInSeconds 86400*30)
public class SessionConfig {
}maxInactiveIntervalInSeconds 设置session失效时间使用redis session之后原boot的sever.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’
tspring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4t(spring:session:expirations:1472976480000其中 1472976480000为失效时间意思是这个时间后session失效db031986-8ecc-48d6-b471-b137a3ed6bc4t 为sessionid登录http://localhost:8080/uid发现会一致就说明session 已经在redis里面进行有效的管理了。
如何在两台或者多台中共享session
其实就是按照上面的步骤在另一个项目中再次配置一次启动后就进行了session共享。本文所有示例https://github.com/ityouknow/spring-boot-starter