激情久久久_欧美视频区_成人av免费_不卡视频一二三区_欧美精品在欧美一区二区少妇_欧美一区二区三区的

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Spring Boot中Redis數(shù)據(jù)庫的使用實(shí)例

Spring Boot中Redis數(shù)據(jù)庫的使用實(shí)例

2020-09-06 15:42心碎落地的聲音 Java教程

Spring Boot中除了對常用的關(guān)系型數(shù)據(jù)庫提供了優(yōu)秀的自動化支持之外,對于很多NoSQL數(shù)據(jù)庫一樣提供了自動化配置的支持。本篇文章主要介紹了Spring Boot中Redis的使用實(shí)例代碼,有興趣的開業(yè)了解一下。

spring boot對常用的數(shù)據(jù)庫支持外,對nosql 數(shù)據(jù)庫也進(jìn)行了封裝自動化。

redis介紹

Redis是目前業(yè)界使用最廣泛的內(nèi)存數(shù)據(jù)存儲。相比memcached,Redis支持更豐富的數(shù)據(jù)結(jié)構(gòu),例如hashes, lists, sets等,同時(shí)支持?jǐn)?shù)據(jù)持久化。除此之外,Redis還提供一些類數(shù)據(jù)庫的特性,比如事務(wù),HA,主從庫??梢哉fRedis兼具了緩存系統(tǒng)和數(shù)據(jù)庫的一些特性,因此有著豐富的應(yīng)用場景。本文介紹Redis在Spring Boot中兩個(gè)典型的應(yīng)用場景。

如何使用

1、引入 spring-boot-starter-redis

?
1
2
3
4
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-redis</artifactId>
</dependency>

 2、添加配置文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# REDIS (RedisProperties)
# Redis數(shù)據(jù)庫索引(默認(rèn)為0
spring.redis.database=0
# Redis服務(wù)器地址
spring.redis.host=192.168.0.58
# Redis服務(wù)器連接端口
spring.redis.port=6379
# Redis服務(wù)器連接密碼(默認(rèn)為空)
spring.redis.password=
# 連接池最大連接數(shù)(使用負(fù)值表示沒有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0
# 連接超時(shí)時(shí)間(毫秒)
spring.redis.timeout=0

3、添加cache的配置類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
@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);
    //設(shè)置緩存過期時(shí)間
    //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、好了,接下來就可以直接使用了

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@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", "111");
    Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));
  }
  
  @Test
  public void testObj() throws Exception {
    User user=new User("[email protected]", "aa", "aa123456", "aa","123");
    ValueOperations<String, User> operations=redisTemplate.opsForValue();
    operations.set("com.neox", user);
    operations.set("com.neo.f", user,1,TimeUnit.SECONDS);
    Thread.sleep(1000);
    //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());
  }
}

以上都是手動使用的方式,如何在查找數(shù)據(jù)庫的時(shí)候自動使用緩存呢,看下面;

4、自動根據(jù)方法生成緩存

?
1
2
3
4
5
6
7
@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
  User user=userRepository.findByUserName("aa");
  System.out.println("若下面沒出現(xiàn)“無緩存的時(shí)候調(diào)用”字樣且能打印出數(shù)據(jù)表示測試成功");
  return user;
}

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

共享Session-spring-session-data-redis

分布式系統(tǒng)中,sessiong共享有很多的解決方案,其中托管到緩存中應(yīng)該是最常用的方案之一,

Spring Session官方說明

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

如何使用

1、引入依賴

?
1
2
3
4
<dependency>
  <groupId>org.springframework.session</groupId>
  <artifactId>spring-session-data-redis</artifactId>
</dependency>

2、Session配置:

?
1
2
3
4
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)
public class SessionConfig {
}

maxInactiveIntervalInSeconds: 設(shè)置Session失效時(shí)間,使用Redis Session之后,原Boot的server.session.timeout屬性不再生效

好了,這樣就配置好了,我們來測試一下

3、測試

添加測試方法獲取sessionid

?
1
2
3
4
5
6
7
8
9
@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*'

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

其中 1472976480000為失效時(shí)間,意思是這個(gè)時(shí)間后session失效,db031986-8ecc-48d6-b471-b137a3ed6bc4 為sessionId,登錄http://localhost:8080/uid 發(fā)現(xiàn)會一致,就說明session 已經(jīng)在redis里面進(jìn)行有效的管理了。

如何在兩臺或者多臺中共享session

其實(shí)就是按照上面的步驟在另一個(gè)項(xiàng)目中再次配置一次,啟動后自動就進(jìn)行了session共享。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:http://blog.csdn.net/linabc123000/article/details/69231060

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: www69xxxxx| 欧美 日韩 亚洲 中文 | videos高潮 | 久草在线观看福利视频 | 国产视频在线一区 | 午夜视频观看 | 日韩av片网站 | 一区二区三区日韩 | 一本视频在线观看 | 欧美亚洲国产一区 | 久久久久国 | 亚洲国产精品久久久久久久 | 成人一级黄色片 | 免费看性xxx高清视频自由 | 久久久久国产精品久久久久 | 国产精品免费一区二区三区都可以 | 黄wwww| 中国fx性欧美xxxx | 日韩av片在线免费观看 | 欧美成年人在线视频 | 久久影院免费观看 | www.guochanav.com| 88xx成人永久免费观看 | 久久精热 | 人成免费a级毛片 | 欧美特黄a | 成人免费观看49www在线观看 | 亚洲视频综合网 | 91,视频免费看 | 七首小情歌泰剧在线播放 | 欧美一极视频 | 成人亚洲一区二区 | 久久综合久久综合久久 | 久久久新| 88xx成人永久免费观看 | 国产免费乱淫av | 一级电影中文字幕 | 久久久国产精品电影 | 91视频官网| 黄色高清免费 | 黄色大片www |