Redis在項(xiàng)目中的使用(JedisPool方式)
springboot中redis相關(guān)配置
1、pom.xml中引入依賴(lài)
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> </dependency>
2、springboot的習(xí)慣優(yōu)于配置。也在項(xiàng)目中使用了application.yml文件配置mysql的基本配置項(xiàng)。這里也在application.yml里面配置redis的配置項(xiàng)。
spring:
datasource:
# 驅(qū)動(dòng)配置信息
url: jdbc:mysql://localhost:3306/spring_boot?useUnicode=true&characterEncoding=utf8
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
# 連接池的配置信息
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 1
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
maxOpenPreparedStatements: 20
redis:
host: 127.0.0.1
port: 6379
password: pass1234
pool:
max-active: 100
max-idle: 10
max-wait: 100000
timeout: 0
springboot中redis相關(guān)類(lèi)
- 項(xiàng)目操作redis是使用的RedisTemplate方式,另外還可以完全使用JedisPool和Jedis來(lái)操作redis。整合的內(nèi)容也是從網(wǎng)上收集整合而來(lái),網(wǎng)上整合的方式和方法非常的多,有使用注解形式的,有使用Jackson2JsonRedisSerializer來(lái)序列化和反序列化key value的值等等,很多很多。這里使用的是我認(rèn)為比較容易理解和掌握的,基于JedisPool配置,使用RedisTemplate來(lái)操作redis的方式。
redis單獨(dú)放在一個(gè)包redis里,在包里先創(chuàng)建RedisConfig.java文件。
RedisConfig.java
@Configuration
@EnableAutoConfiguration
public class RedisConfig {
@Bean
@ConfigurationProperties(prefix = "spring.redis.pool")
public JedisPoolConfig getRedisConfig(){
JedisPoolConfig config = new JedisPoolConfig();
return config;
}
@Bean
@ConfigurationProperties(prefix = "spring.redis")
public JedisConnectionFactory getConnectionFactory() {
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setUsePool(true);
JedisPoolConfig config = getRedisConfig();
factory.setPoolConfig(config);
return factory;
}
@Bean
public RedisTemplate<?, ?> getRedisTemplate() {
JedisConnectionFactory factory = getConnectionFactory();
RedisTemplate<?, ?> template = new StringRedisTemplate(factory);
return template;
}
}
- 在包里創(chuàng)建RedisService接口的實(shí)現(xiàn)類(lèi)RedisServiceImpl,這個(gè)類(lèi)實(shí)現(xiàn)了接口的所有方法。
RedisServiceImpl.java
@Service("redisService")
public class RedisServiceImpl implements RedisService {
@Resource
private RedisTemplate<String, ?> redisTemplate;
@Override
public boolean set(final String key, final String value) {
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
connection.set(serializer.serialize(key), serializer.serialize(value));
return true;
}
});
return result;
}
@Override
public String get(final String key) {
String result = redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
byte[] value = connection.get(serializer.serialize(key));
return serializer.deserialize(value);
}
});
return result;
}
@Override
public boolean expire(final String key, long expire) {
return redisTemplate.expire(key, expire, TimeUnit.SECONDS);
}
@Override
public boolean remove(final String key) {
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
RedisSerializer<String> serializer = redisTemplate.getStringSerializer();
connection.del(key.getBytes());
return true;
}
});
return result;
}
}
在這里execute()方法具體的底層沒(méi)有去研究,只知道這樣能實(shí)現(xiàn)對(duì)于redis數(shù)據(jù)的操作。
redis保存的數(shù)據(jù)會(huì)在內(nèi)存和硬盤(pán)上存儲(chǔ),所以需要做序列化;這個(gè)里面使用的StringRedisSerializer來(lái)做序列化,不過(guò)這個(gè)方式的泛型指定的是String,只能傳String進(jìn)來(lái)。所以項(xiàng)目中采用json字符串做redis的交互。
到此,redis在springboot中的整合已經(jīng)完畢,下面就來(lái)測(cè)試使用一下。
5. springboot項(xiàng)目中使用redis
在這里就直接使用springboot項(xiàng)目中自帶的單元測(cè)試類(lèi)SpringbootApplicationTests進(jìn)行測(cè)試。
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootApplicationTests {
private JSONObject json = new JSONObject();
@Autowired
private RedisService redisService;
@Test
public void contextLoads() throws Exception {
}
/**
* 插入字符串
*/
@Test
public void setString() {
redisService.set("redis_string_test", "springboot redis test");
}
/**
* 獲取字符串
*/
@Test
public void getString() {
String result = redisService.get("redis_string_test");
System.out.println(result);
}
/**
* 插入對(duì)象
*/
@Test
public void setObject() {
Person person = new Person("person", "male");
redisService.set("redis_obj_test", json.toJSONString(person));
}
/**
* 獲取對(duì)象
*/
@Test
public void getObject() {
String result = redisService.get("redis_obj_test");
Person person = json.parseObject(result, Person.class);
System.out.println(json.toJSONString(person));
}
/**
* 插入對(duì)象List
*/
@Test
public void setList() {
Person person1 = new Person("person1", "male");
Person person2 = new Person("person2", "female");
Person person3 = new Person("person3", "male");
List<Person> list = new ArrayList<>();
list.add(person1);
list.add(person2);
list.add(person3);
redisService.set("redis_list_test", json.toJSONString(list));
}
/**
* 獲取list
*/
@Test
public void getList() {
String result = redisService.get("redis_list_test");
List<String> list = json.parseArray(result, String.class);
System.out.println(list);
}
@Test
public void remove() {
redisService.remove("redis_test");
}
}
class Person {
private String name;
private String sex;
public Person() {
}
public Person(String name, String sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
在這里先是用@Autowired注解把redisService注入進(jìn)來(lái),然后由于是使用json字符串進(jìn)行交互,所以引入fastjson的JSONObject類(lèi)。然后為了方便,直接在這個(gè)測(cè)試類(lèi)里面加了一個(gè)Person的內(nèi)部類(lèi)。
一共測(cè)試了:對(duì)于string類(lèi)型的存取,對(duì)于object類(lèi)型的存取,對(duì)于list類(lèi)型的存取,其實(shí)本質(zhì)都是轉(zhuǎn)成了json字符串。還有就是根據(jù)key來(lái)執(zhí)行remove操作。
獲取字符串:

獲取對(duì)象:

獲取list:

redis管理客戶(hù)端數(shù)據(jù):

到此,測(cè)試完成,對(duì)于常用的一些數(shù)據(jù)類(lèi)型的轉(zhuǎn)換存取操作也基本調(diào)試通過(guò)。所以本文對(duì)于springboot整合redis到此結(jié)束。
到此這篇關(guān)于Redis在項(xiàng)目中的使用(JedisPool方式)的文章就介紹到這了,更多相關(guān)Redis項(xiàng)目中使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Redis+Caffeine實(shí)現(xiàn)分布式二級(jí)緩存組件實(shí)戰(zhàn)教程
這篇文章主要介紹了Redis+Caffeine實(shí)現(xiàn)分布式二級(jí)緩存組件實(shí)戰(zhàn)教程,介紹了分布式二級(jí)緩存的優(yōu)勢(shì),使用組件的方法,通過(guò)示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
Redis中5種數(shù)據(jù)結(jié)構(gòu)的使用場(chǎng)景介紹
這篇文章主要介紹了Redis中5種數(shù)據(jù)結(jié)構(gòu)的使用場(chǎng)景介紹,本文對(duì)Redis中的5種數(shù)據(jù)類(lèi)型String、Hash、List、Set、Sorted Set做了講解,需要的朋友可以參考下2014-09-09
淺談Redis?中的過(guò)期刪除策略和內(nèi)存淘汰機(jī)制
本文主要介紹了Redis?中的過(guò)期刪除策略和內(nèi)存淘汰機(jī)制,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-04-04
關(guān)于Redis未授權(quán)訪(fǎng)問(wèn)的問(wèn)題
這篇文章主要介紹了Redis未授權(quán)訪(fǎng)問(wèn)的問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-07-07
Redis實(shí)現(xiàn)分布式鎖的幾種方法總結(jié)
這篇文章主要介紹了Redis實(shí)現(xiàn)分布式鎖的幾種方法總結(jié)的相關(guān)資料, Redis實(shí)現(xiàn)與Zookeeper實(shí)現(xiàn)和數(shù)據(jù)庫(kù)實(shí)現(xiàn),需要的朋友可以參考下2017-07-07
緩存穿透是指當(dāng)用戶(hù)在查詢(xún)一條數(shù)據(jù)的時(shí)候,而此時(shí)數(shù)據(jù)庫(kù)和緩存卻沒(méi)有關(guān)于這條數(shù)據(jù)的任何記錄,而這條數(shù)據(jù)在緩存中沒(méi)找到就會(huì)向數(shù)據(jù)庫(kù)請(qǐng)求獲取數(shù)據(jù)。用戶(hù)拿不到數(shù)據(jù)時(shí),就會(huì)一直發(fā)請(qǐng)求,查詢(xún)數(shù)據(jù)庫(kù),這樣會(huì)對(duì)數(shù)據(jù)庫(kù)的訪(fǎng)問(wèn)造成很大的壓力2022-07-07
簡(jiǎn)單粗暴的Redis數(shù)據(jù)備份和恢復(fù)方法
這里我們來(lái)講解一個(gè)簡(jiǎn)單粗暴的Redis數(shù)據(jù)備份和恢復(fù)方法,有一個(gè)在不同主機(jī)上遷移Redis數(shù)據(jù)的示例,還有一個(gè)備份腳本實(shí)現(xiàn)的關(guān)鍵點(diǎn)提示,一起來(lái)看一下:2016-06-06

