導航:首頁 > 文件管理 > springredis配置文件詳解

springredis配置文件詳解

發布時間:2023-05-23 09:47:36

⑴ spring boot + redis 實現session共享分析

HttpSession是由servelet容器進行管理的。而我們常用的應用容器有 Tomcat/Jetty等, 這些容器的HttpSession都是存放在對應的應用容器的岩彎內存中,在分布式集群的環境下,通常我們使用Nginx或者LVS、Zuul等進行反向代理和負載均衡,因此用戶請求是由一組提供相同服務的應用來進行處理,而用戶最終請求到的服務由Nginx和LVS、Zuul進行確定。

那麼問題就來了,我們怎樣保證多個相同的應用共享同一份session數據?對於這種問題Spring為我們提供了Spring Session進行管理我們的HttpSession。項目地址: http://projects.spring.io/spring-session/

1.添加Spring session的包,而Spring session 是將HttpSession存放在Redis中,因此啟唯需要添加Redis的包。我們這里是用了悄棗培Spring boot進行配置Rdies。

2.使用@EnableRedisHttpSession註解進行配置啟用使用Spring session。

3.配置我們的Redis鏈接,我們這里使用的是Spring Boot作為基礎進行配置,因此我們只需要在YML或者Properties配置文件添加Redis的配置即可。

4.創建請求的控制器來進行確定我們是否啟用Session 共享。

5.將當前的工程拷貝一份.

通過上面請求顯示的結果我們可以看出使用的是同一個Seesion,我們也可以查看下存在Redis中的Session。我這里使用RDM進行查看,我們還可以查看Session的屬性。從圖可以看出我們存進入的url屬性。

我們從啟動Spring Session的配置註解@EnableRedisHttpSession開始。
1.我們可以通過@EnableRedisHttpSession可以知道,Spring Session是通過RedisHttpSessionConfiguration類進行配置的。

2.我們在RedisHttpSessionConfiguration類種的注釋可以知道,該類是用於創建一個過濾SessionRepositoryFilter。

3.探究下SessionRepositoryFilter類是在哪裡創建創建過程作用。
(1)哪裡創建:
通過搜索RedisHttpSessionConfiguration發現SessionRepositoryFilter的創建不是在RedisHttpSessionConfiguration,而是在父類中創建。

(2)SessionRepositoryFilter創建過程:

這里我們可以總結下:
Redis確保鏈接的情況下。
1.創建sessionRedisTemplate
2.創建
3.創建SessionRepositoryFilter

(3)SessionRepositoryFilter的作用:
SessionRepositoryFilter的主要作用接管Seession的管理。我們可以從下面幾個點知道為什麼?

4.我們研究下是怎樣接管Session?

(1)存儲Session的過程

當調用SessionRepositoryFilter.this.sessionRepository.save(session)完畢後,會判斷當前的SessionId是否與請求的中的Cookie中SessionId一致,若不一致的情況下會調用onNewSession()方法,我們可以通過配置類的可以看到使用的是
CookieHttpSessionStrategy();
從CookieHttpSessionStrategy.onNewSession()方法可以看到是將SessionId寫到Cookie中。

(2)獲取Session的過程

我們根據源碼的分析可以知道:
1.Spring Session 是通過SessionRepositoryFilter過濾器進行攔截,然後通過繼承HttpServletRequestWrapper進行管理Session。

2.Spring Session 為我們提供了3中存放的策略而每種策略提供對應的註解啟動。分別為:
(1)NoSql形式的MongoDb:@EnableMongoHttpSession
(2)持久化形式的JDBC:@EnableJdbcHttpSession
(3)緩存形式的Redis:@EnableRedisHttpSession

3.Spring Session 共享Session過程:
(1)先過程過濾器存儲將SessionID存放到本地的Cookie 和Redis中。
如果本地沒有啟用Cookie的情況下,Spring Session也就不能使用。
(2)獲取Session的時候,先從請求中獲取Session,Session不為空的情況下直接返回Session,若當前的Session為空的情況下,從Cookie中獲取SessionId,判斷SessionId不為空,再從Redis中獲取Session,若從Redis中獲取到的Session不為空將Session存放到請求中,再返回Session,如果從Redis中獲取的Session為空,再創建新的Session並且添加到請求中,後返回Session。

⑵ springboot--redis配置

基於spring.version:4.x;
4.2.4.RELEASE
不同spring版本敏枯世對應的redis版本也不一敗慎樣,配置橋肢類也會不同。

添加pom:

redis參數配置:RedisConfig.class

redis配置類:RedisConfiguration.class

redis工具類:redisUtils.class

示例使用

⑶ 3分鍾搞定springboot整合redis

不多說直接上代碼

<!-- redis -->

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-redis</artifactId>

<exclusions>

<exclusion>

<groupId>redis.clients</groupId>

<artifactId>jedis</artifactId>

</exclusion>

<exclusion>

<groupId>io.lettuce</groupId>

<artifactId>lettuce-core</artifactId>

</exclusion>

</exclusions>

</dependency>

<!-- 添加jedis客戶端 -->

<dependency>

<groupId>redis.clients</groupId>

<artifactId>jedis</artifactId>

</dependency>

<!--spring2.0集成redis所需common-pool2-->

<!-- 必須加上,jedis依賴此 -->

<dependency>

<groupId>org.apache.commons<枯賣/groupId>

<artifactId>commons-pool2</artifactId>

<version>2.5.0</version>

</dependency>

<!-- 將作為Redis對象序列化器 -->

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>fastjson</artifactId>

<version>1.2.47</version>

</dependency>

#Matser的ip地址

redis.hostName=172.16.44.148

#埠號

redis.port=6379

#如果有密碼

redis.password=

#客戶端超時時間單位是毫秒 默認是2000

redis.timeout=10000

#最大空閑數

redis.maxIdle=300

#連接池的最大資料庫連接數。設為0表示無限制,如果是jedis 2.4以後用redis.maxTotal

#redis.maxActive=600

#控制一個pool可分配多少個jedis實例,用來替換上面的redis.maxActive,如果是jedis 2.4以後用該屬性

redis.maxTotal=1000

#最大建立連接等待時間。如果超過此時間將接到異常。設為-1表示無限制。

redis.maxWaitMillis=1000

#連接的最小空閑賣沒時間沒配逗 默認1800000毫秒(30分鍾)

redis.minEvictableIdleTimeMillis=300000

#每次釋放連接的最大數目,默認3

redis.numTestsPerEvictionRun=1024

#逐出掃描的時間間隔(毫秒) 如果為負數,則不運行逐出線程, 默認-1

redis.timeBetweenEvictionRunsMillis=30000

#是否在從池中取出連接前進行檢驗,如果檢驗失敗,則從池中去除連接並嘗試取出另一個

redis.testOnBorrow=true

#在空閑時檢查有效性, 默認false

redis.testWhileIdle=true

package com.junsi.demo.config;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.serializer.;

import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.junsi.demo.utils.RedisUtil;

import redis.clients.jedis.JedisPoolConfig;

/**

* Redis配置類

* @author pzx

* 2019年6月8日

*/

@Configuration

@PropertySource("classpath:redis.properties")

public class RedisConfig {

@Value("${redis.maxIdle}")

private Integer maxIdle;

@Value("${redis.maxTotal}")

private Integer maxTotal;

@Value("${redis.maxWaitMillis}")

private Integer maxWaitMillis;

@Value("${redis.minEvictableIdleTimeMillis}")

private Integer minEvictableIdleTimeMillis;

@Value("${redis.numTestsPerEvictionRun}")

private Integer numTestsPerEvictionRun;

@Value("${redis.timeBetweenEvictionRunsMillis}")

private long timeBetweenEvictionRunsMillis;

@Value("${redis.testOnBorrow}")

private boolean testOnBorrow;

@Value("${redis.testWhileIdle}")

private boolean testWhileIdle;

@Value("${spring.redis.cluster.nodes}")

private String clusterNodes;

@Value("${spring.redis.cluster.max-redirects}")

private Integer mmaxRedirectsac;

/**

* JedisPoolConfig 連接池

* @return

*/

@Bean

public JedisPoolConfig jedisPoolConfig() {

JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();

// 最大空閑數

jedisPoolConfig.setMaxIdle(maxIdle);

// 連接池的最大數據庫連接數

jedisPoolConfig.setMaxTotal(maxTotal);

// 最大建立連接等待時間

jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);

// 逐出連接的最小空閑時間 默認1800000毫秒(30分鍾)

jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);

// 每次逐出檢查時 逐出的最大數目 如果為負數就是 : 1/abs(n), 默認3

jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);

// 逐出掃描的時間間隔(毫秒) 如果為負數,則不運行逐出線程, 默認-1

jedisPoolConfig.(timeBetweenEvictionRunsMillis);

// 是否在從池中取出連接前進行檢驗,如果檢驗失敗,則從池中去除連接並嘗試取出另一個

jedisPoolConfig.setTestOnBorrow(testOnBorrow);

// 在空閑時檢查有效性, 默認false

jedisPoolConfig.setTestWhileIdle(testWhileIdle);

return jedisPoolConfig;

}

/**

* @param jedisPoolConfig

* @return

*/

@Bean

public JedisConnectionFactory JedisConnectionFactory(JedisPoolConfig jedisPoolConfig){

JedisConnectionFactory JedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig);

//連接池

JedisConnectionFactory.setPoolConfig(jedisPoolConfig);

//IP地址

JedisConnectionFactory.setHostName("172.16.44.148");

//埠號

JedisConnectionFactory.setPort(6379);

//如果Redis設置有密碼

//JedisConnectionFactory.setPassword(password);

//客戶端超時時間單位是毫秒

JedisConnectionFactory.setTimeout(5000);

return JedisConnectionFactory;

}

/**

* 實例化 RedisTemplate 對象

*

* @return

*/

@Bean

public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {

RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

initDomainRedisTemplate(redisTemplate, redisConnectionFactory);

return redisTemplate;

}

/**

* 設置數據存入 redis 的序列化方式,並開啟事務

*

* @param redisTemplate

* @param factory

*/

private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {

//如果不配置Serializer,那麼存儲的時候預設使用String,如果用User類型存儲,那麼會提示錯誤User can't cast to String!

redisTemplate.setKeySerializer(new StringRedisSerializer());

redisTemplate.setHashKeySerializer(new StringRedisSerializer());

redisTemplate.setHashValueSerializer(new ());

redisTemplate.setValueSerializer(new ());

// 開啟事務

redisTemplate.setEnableTransactionSupport(true);

redisTemplate.setConnectionFactory(factory);

}

@Bean(name = "redisUtil")

public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {

RedisUtil redisUtil = new RedisUtil();

redisUtil.setRedisTemplate(redisTemplate);

return redisUtil;

}

}

⑷ windows環境下Redis+Spring緩存實例

一、Redis了解

1.1、Redis介紹:

redis是一個key-value存儲系統。和Memcached類似,它支持存儲的value類型相對更多,包括string(字元串)、list(鏈表)、set(集合)、zset(sorted set –有序集合)和hash(哈希類型)。這些數據類型都支持push/pop、add/remove及取交集並集和差集及更豐富的操作,而且這些操作都是原子性的。在此基礎上,redis支持各種不同方式的排序。與memcached一樣,為了保證效率,數據都是緩存在內存中。區別的是redis會周期性的把更新的數據寫入磁碟或者把修改操作寫入追加的記錄文件,並且在此基礎上實現了master-slave(主從)同步。

Redis資料庫完全在內存中,使用磁碟僅用於持久性。相比許多鍵值數據存儲,Redis擁有一套較為豐富的數據類型。Redis可以將數據復制到任意數量的從伺服器。

1.2、Redis優點:

(1)異常快速:Redis的速度非常快,每秒能執行約11萬集合,每秒約81000+條記錄。

(2)支持豐富的數據類型:Redis支持最大多數開發人員已經知道像列表,集合,有序集合,散列數據類型。這使得它非常容易解決各種各樣的問題,因為我們知道哪些問題是可以處理通過它的數據類型更好。

(3)操作都是原子性:所有Redis操作是原子的,這保證了如果兩個客戶端同時訪問的Redis伺服器將獲得更新後的值。

(4)多功能實用工具:Redis是一個多實用的工具,可以在多個用例如緩存,消息,隊列使用(Redis原生支持發布/訂閱),任何短暫的數據,應用程序,如Web應用程序會話,網頁命中計數等。

1.3、Redis缺點:

(1)單線程

(2)耗內存

二、64位windows下Redis安裝

Redis官方是不支持windows的,但是Microsoft Open Tech group 在 GitHub上開發了一個Win64的版本,下載地址:https://github.com/MSOpenTech/redis/releases。注意只支持64位哈。

小寶鴿是下載了Redis-x64-3.0.500.msi進行安裝。安裝過程中全部採取默認即可。

安裝完成之後可能已經幫你開啟了Redis對應的服務,博主的就是如此。查看資源管理如下,說明已經開啟:

已經開啟了對應服務的,我們讓它保持,下面例子需要用到。如果沒有開啟的.,我們命令開啟,進入Redis的安裝目錄(博主的是C:Program FilesRedis),然後如下命令開啟:

redis-server redis.windows.conf

OK,下面我們進行實例。

三、詳細實例

本工程採用的環境:Eclipse + maven + spring + junit

3.1、添加相關依賴(spring+junit+redis依賴),pom.xml:

4.0.0 com.luo redis_project 0.0.1-SNAPSHOT 3.2.8.RELEASE 4.10 org.springframework spring-core ${spring.version} org.springframework spring-webmvc ${spring.version} org.springframework spring-context ${spring.version} org.springframework spring-context-support ${spring.version} org.springframework spring-aop ${spring.version} org.springframework spring-aspects ${spring.version} org.springframework spring-tx ${spring.version} org.springframework spring-jdbc ${spring.version} org.springframework spring-web ${spring.version} junit junit ${junit.version} test org.springframework spring-test ${spring.version} test org.springframework.data spring-data-redis 1.6.1.RELEASE redis.clients jedis 2.7.3

3.2、spring配置文件application.xml:

<"1.0" encoding="UTF-8"> classpath:properties/*.properties

3.3、Redis配置參數,redis.properties:

#redis中心#綁定的主機地址redis.host=127.0.0.1#指定Redis監聽埠,默認埠為6379redis.port=6379#授權密碼(本例子沒有使用)redis.password=123456 #最大空閑數:空閑鏈接數大於maxIdle時,將進行回收redis.maxIdle=100 #最大連接數:能夠同時建立的「最大鏈接個數」redis.maxActive=300 #最大等待時間:單位msredis.maxWait=1000 #使用連接時,檢測連接是否成功 redis.testOnBorrow=true#當客戶端閑置多長時間後關閉連接,如果指定為0,表示關閉該功能redis.timeout=10000

3.4、添加介面及對應實現RedisTestService.java和RedisTestServiceImpl.java:

package com.luo.service; public interface RedisTestService { public String getTimestamp(String param);}

package com.luo.service.impl; import org.springframework.stereotype.Service;import com.luo.service.RedisTestService; @Servicepublic class RedisTestServiceImpl implements RedisTestService { public String getTimestamp(String param) { Long timestamp = System.currentTimeMillis(); return timestamp.toString(); } }

3.5、本例採用spring aop切面方式進行緩存,配置已在上面spring配置文件中,對應實現為MethodCacheInterceptor.java:

package com.luo.redis.cache; import java.io.Serializable;import java.util.concurrent.TimeUnit;import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations; public class MethodCacheInterceptor implements MethodInterceptor { private RedisTemplate redisTemplate; private Long defaultCacheExpireTime = 10l; // 緩存默認的過期時間,這里設置了10秒 public Object invoke(MethodInvocation invocation) throws Throwable { Object value = null; String targetName = invocation.getThis().getClass().getName(); String methodName = invocation.getMethod().getName(); Object[] arguments = invocation.getArguments(); String key = getCacheKey(targetName, methodName, arguments); try { // 判斷是否有緩存 if (exists(key)) { return getCache(key); } // 寫入緩存 value = invocation.proceed(); if (value != null) { final String tkey = key; final Object tvalue = value; new Thread(new Runnable() { public void run() { setCache(tkey, tvalue, defaultCacheExpireTime); } }).start(); } } catch (Exception e) { e.printStackTrace(); if (value == null) { return invocation.proceed(); } } return value; } /** * 創建緩存key * * @param targetName * @param methodName * @param arguments */ private String getCacheKey(String targetName, String methodName, Object[] arguments) { StringBuffer sbu = new StringBuffer(); sbu.append(targetName).append("_").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { sbu.append("_").append(arguments[i]); } } return sbu.toString(); } /** * 判斷緩存中是否有對應的value * * @param key * @return */ public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * 讀取緩存 * * @param key * @return */ public Object getCache(final String key) { Object result = null; ValueOperations operations = redisTemplate .opsForValue(); result = operations.get(key); return result; } /** * 寫入緩存 * * @param key * @param value * @return */ public boolean setCache(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations operations = redisTemplate .opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public void setRedisTemplate( RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; }}

3.6、單元測試相關類:

package com.luo.baseTest; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //指定bean注入的配置文件 @ContextConfiguration(locations = { "classpath:application.xml" }) //使用標準的JUnit @RunWith注釋來告訴JUnit使用Spring TestRunner @RunWith(SpringJUnit4ClassRunner.class) public class SpringTestCase extends { }

package com.luo.service; import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired; import com.luo.baseTest.SpringTestCase; public class RedisTestServiceTest extends SpringTestCase { @Autowired private RedisTestService redisTestService; @Test public void getTimestampTest() throws InterruptedException{ System.out.println("第一次調用:" + redisTestService.getTimestamp("param")); Thread.sleep(2000); System.out.println("2秒之後調用:" + redisTestService.getTimestamp("param")); Thread.sleep(11000); System.out.println("再過11秒之後調用:" + redisTestService.getTimestamp("param")); } }

3.7、運行結果:

四、源碼下載:redis-project().rar

以上就是本文的全部內容,希望對大家的學習有所幫助。

⑸ 怎麼看spring-bootspring-data-redis

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=0
# Redis伺服器地址
spring.redis.host=192.168.0.58
# Redis伺服器連接埠
spring.redis.port=6379
# Redis伺服器連接密碼(默認為空)
spring.redis.password=
# 連接池最大連接數(使用負值表示沒有限制)
spring.redis.pool.max-active=8
# 連接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 連接池中的最大空閑連接
spring.redis.pool.max-idle=8
# 連接池中的最小空閑連接
spring.redis.pool.min-idle=0
# 連接超時時間(毫秒)
spring.redis.timeout=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();
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)
@(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());
}
}

以上都是手動使用的方式,如何在查找資料庫的時候自動使用緩存呢,看下面;

4、自動根據方法生成緩存
@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
User user=userRepository.findByUserName("aa");
System.out.println("若下面沒出現「無緩存的時候調用」字樣且能列印出數據表示測試成功");
return user;
}

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

⑹ Spring cloud 配置 Redis 單實例項目

使用centOS安裝 redis 5.0.5版本,通過spring cloud配置中心設置配置服務

伺服器地址 192.168.56.150

redis 安裝目錄在 /root/redis-5.0.5目錄中,修改配置文件redis.conf

配置完成啟動redis服蠢鍵舉務

設置完成,重啟配置中心服務亮攔

-在order項目工程中,新建一個介面類如帶碧:

訪問介面 http://127.0.0.1:8010/order/redis
集成的配置完成

⑺ 【原創】Springboot Redis配置總結( 基於spring-boot-data-redis-stater )

本配置方法主要基於各組件都低於目前市面最新版本的組件測試。

本配置方法主弊源要租橋態基於各組件都低於目前市消此面最新版本的組件測試。

⑻ 如何在spring配置文件中配置jedis連接池主從redis

xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd"
default-lazy-init="false">

<!-- 連接池配置. -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- 連接池中最大連接數。高版本:maxTotal,低版本:maxActive -->
<property name="maxTotal" value="8" />
<!-- 連接池中最大空閑的連接數. -->
<property name="maxIdle" value="4" />
<!-- 連接池中最少空閑的連接數. -->
<property name="minIdle" value="1" />
<!-- 當連接池譽拍資源耗盡時,調用者最大阻塞的時間,超時將跑出異常。單位,毫秒數;默認為-1.表示永不超時。高版本:maxWaitMillis,低版本:maxWait -->
<property name="maxWaitMillis" value="5000" />
<!-- 連接空閑的最小時間,達到此值後空閑連接將可能會被移除。負值(-1)表示不移除. -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<!-- 對於「空閑鏈接」檢測線程而言,每次檢測的鏈接資源的個數。默認為3 -->
<property name="numTestsPerEvictionRun" value="3" />
<!-- 「空閑鏈接」檢測線程,檢測的周期,毫秒數。如果為負值,表示不運讓巧行「檢測線程」。默認為-1. -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- testOnBorrow:向調用者輸出「鏈接」資源時,是否檢測是有有效,如果無效則從連接池坦虛鍵中移除,並嘗試獲取繼續獲取。默認為false。建議保持默認值. -->
<!-- testOnReturn:向連接池「歸還」鏈接時,是否檢測「鏈接」對象的有效性。默認為false

⑼ Spring Boot如何整合Redis

Spring Boot是目前非常流行的Java Web開發框架,Redis是非關系型資料庫的一種,以鍵值對的形式存儲。Spring對Redis的支持是通過Spring Data Redis來實現的,給我們提供了RedisTemplate和StringRedisTemplate兩種模板來操作數據。Spring Boot框架也提供了對Redis的支持,下面我們來講一下Spring Boot框架整合Redis的步驟。

工具/材料

IntelliJ IDEA

特別提示

在Spring Boot整合Redis前本機需安裝Redis,另外可以使用RedisDesktopManager這個Redis這個桌面管理工具查看Redis中的數據。

⑽ SpringBoot整合SpringSeesion實現Redis緩存

使用Spring Boot開發項目時我們經常需要存儲Session,因為Session中會存一些用戶信息或者登錄信息。傳統的web服務是將session存儲在內存中的,一旦服務掛了,session也就消失了,這時候我們就需要將session存儲起來,而Redis就是用來緩存seesion的一種非關系型資料庫,我們可以通過配置或者註解的方式將Spring Boot和Redis整合。而在分布式系統中又會涉及到session共享的問題,多個服務同時部署時session需要共享,Spring Session可以幫助我們實現這一功能。將Spring Session集成到Spring Boot框架中並使用Redis進行緩存是目前非常流行的解決方案,接下來就跟著我一起學習吧。

工具/材料

IntelliJ IDEA

首先我們創建一個Spring Boot 2.x的項目,在application.properties配置文件中添加Redis的配置,Spring和Redis的整合可以參考我其他的文章,此處不再詳解。我們設置服務埠server.port為8080埠用於啟動第一個服務。

接下來我們需要在pom文件中添加spring-boot-starter-data-redis和spring-session-data-redis這兩個依賴,spring-boot-starter-data-redis用於整合Spring Boot和Redis,spring-session-data-redis集成了spring-session和spring-data-redis,提供了session與redis的整合方案。

接下來我們創建一個配置類RedisSessionConfig,這個類使用@Configuration註解表明這是一個配置類。在這個類上我們同時添加註解@EnableRedisHttpSession,表示開啟Redis的Session管理。如果需要設置失效時間可以使用@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)表示一小時後失效。若同時需要設置Redis的命名空間則使用@EnableRedisHttpSession(maxInactiveIntervalInSeconds=3600, redisNamespace="{spring.session.redis.namespace}") ,其中{spring.session.redis.namespace}表示從配置文件中讀取這個命名空間。

配置完成後我們寫一個測試類SessionController,在這個類中我們寫兩個方法,一個方法用於往session中存數據,一個用於從session中取數據,代碼如下圖所示,我們存取請求的url。啟動類非常簡單,一般都是通用的,我們創建一個名為SpringbootApplication的啟動類,使用main方法啟動。

接下來我們使用Postman分別請求上面兩個介面,先請求存數據介面,再請求取數據介面,結果如下圖所示,我們可以看到數據已從redis中取出。另外需要注意sessionId的值,這是session共享的關鍵。

為了驗證兩個服務是否共享了session,我們修改項目的配置文件,將服務埠server.port改為8090,然後再啟動服務。此時我們不必在請求存數據的介面,只需要修改請求埠號再一次請求取數據的介面即可。由下圖可以看到兩次請求的sessionId值相同,實現了session的共享。

以上我們完成了SpringBoot整合SpringSeesion實現Redis緩存的功能,在此我們還要推薦一個Redis的可視化工具RedisDesktopManager,我們可以配置Redis資料庫的連接,然後便可以非常直觀地查看到存儲到Redis中的session了,如下圖所示,session的命名空間是share,正是從配置文件中讀取到的。

特別提示

如果Redis伺服器是很多項目共用的,非常建議配置命名空間,否則同時打開多個項目的瀏覽器頁面可能會導致session錯亂的現象。

閱讀全文

與springredis配置文件詳解相關的資料

熱點內容
團購是在哪個app 瀏覽:897
打開多個word文檔圖片就不能顯示 瀏覽:855
騰訊新聞怎麼切換版本 瀏覽:269
app安裝失敗用不了 瀏覽:326
桌面文件滑鼠點開會變大變小 瀏覽:536
手機誤刪系統文件開不了機 瀏覽:883
微信兔子甩耳朵 瀏覽:998
android藍牙傳文件在哪裡 瀏覽:354
蘋果6s軟解是真的嗎 瀏覽:310
c語言代碼量大 瀏覽:874
最新網路衛星導航如何使用 瀏覽:425
以下哪些文件屬於圖像文件 瀏覽:774
zycommentjs 瀏覽:414
確認全血細胞減少看哪些數據 瀏覽:265
文件有哪些要求 瀏覽:484
cad打開時會出現兩個文件 瀏覽:65
什麼是轉基因網站 瀏覽:48
手柄設備有問題代碼43 瀏覽:921
怎麼他么怎麼又網路了 瀏覽:649
java會出現內存泄露么 瀏覽:617

友情鏈接