App下載

詳解Java、Spring和Springboot整合Redis數(shù)據(jù)庫(kù)的具體方法

猿友 2021-07-17 10:22:37 瀏覽數(shù) (2015)
反饋

Redis作為一個(gè)開(kāi)源的,基于C語(yǔ)言編寫的,支持網(wǎng)絡(luò)交互的,可基于內(nèi)存可持久化的key-value數(shù)據(jù)庫(kù),在現(xiàn)在的程序開(kāi)發(fā)應(yīng)用中十分的廣泛。本篇文章將為您介紹使用Java、Spring以及Springboot整合Redis數(shù)據(jù)庫(kù)的具體操作方法。

java整合Redis

1、引入依賴或者導(dǎo)入jar包

<dependency>
 <groupId>redis.clients</groupId>
 <artifactId>jedis</artifactId>
 <version>2.9.0</version>
</dependency>

2、代碼實(shí)現(xiàn)

public class JedisTest {
 public static void main(String[] args) {
  //連接redis
  //Jedis jedis=new Jedis("192.168.65.128",6379);

  //使用Jedis連接池
  Jedis jedis=getJedis();
  //操作redis
  jedis.set("name","小白");
  jedis.set("age","19");
  System.out.println("操作成功!");
  jedis.close();
 }

 public static Jedis getJedis(){
  //創(chuàng)建連接池配置對(duì)象
  JedisPoolConfig config=new JedisPoolConfig();
  config.setMaxIdle(10);
  config.setMinIdle(5);
  config.setMaxTotal(100);
  //需要redis的服務(wù)密碼時(shí),使用第一種創(chuàng)建方式
  //JedisPool jedisPool=new JedisPool(config,"192.168.65.128",6379,10000,"root");
  JedisPool jedisPool=new JedisPool(config,"192.168.65.128",6379,10000);
  return jedisPool.getResource();
 }
}

Spring整合Redis

1、添加依賴

<dependency>
 <groupId>org.springframework.data</groupId>
 <artifactId>spring-data-redis</artifactId>
 <version>2.1.8.RELEASE</version>
</dependency>

<dependency>
 <groupId>redis.clients</groupId>
 <artifactId>jedis</artifactId>
 <version>2.9.0</version>
</dependency>

2、redis配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 <!--1、配置redis連接池對(duì)象-->
 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  <!--最大空閑數(shù)-->
  <property name="maxIdle" value="50"/>
  <!--最大連接數(shù)-->
  <property name="maxTotal" value="100"/>
  <!--最大等待時(shí)間-->
  <property name="maxWaitMillis" value="60000"/>
 </bean>

 <!--2、配置redis連接工廠-->
 <bean id="factory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  <!--連接池的配置-->
  <property name="poolConfig" ref="poolConfig"/>
  <!--連接主機(jī)-->
  <property name="hostName" value="192.168.65.128"/>
  <!--端口-->
  <property name="port" value="6379"/>
  <!--密碼-->
  <!--
  當(dāng)出現(xiàn)以下錯(cuò)誤時(shí),說(shuō)明并不需要設(shè)置密碼
  Caused by: redis.clients.jedis.exceptions.JedisDataException: ERR Client sent AUTH, but no password is set
  -->
  <!--<property name="password" value="root"/>-->
 </bean>

 <!--3、配置redis模板對(duì)象-->
 <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  <!--配置連接工廠-->
  <property name="connectionFactory" ref="factory"/>
 </bean>
</beans>

3、注入模板對(duì)象

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:application-redis.xml")
public class RedisTest {
 @Autowired
 private RedisTemplate redisTemplate;

 @Test
 public void test(){
  //redisTemplate.opsForValue().set("name","小黑");
  Object name = redisTemplate.opsForValue().get("name");
  System.out.println(name);
  System.out.println("操作完成");
 }
}

注意:使用Spring(SpringBoot)整合redis后,RedisTemplate對(duì)象會(huì)自帶key和value的序列化功能。在redis的客戶端操作時(shí),獲取的key是被序列化后的key.

思考:為什么Spring要提供一個(gè)序列化的功能? 為了開(kāi)發(fā)者方便將對(duì)象存入redis中??稍趚ml中配置自定義的序列化類型。

 <!--3、配置redis模板對(duì)象-->
 <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  <!--配置連接工廠-->
  <property name="connectionFactory" ref="factory"/>
  <!--配置String類型的key value序列化方式 當(dāng)存儲(chǔ)的key是String類型時(shí),則vlaue也是String類型,且key和value不被序列化-->
  <property name="keySerializer" ref="stringRedisSerializer"/>
  <property name="valueSerializer" ref="stringRedisSerializer"/>
 </bean>
 <!--自定義序列化類型-->
 <bean id="stringRedisSerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
 <!--默認(rèn)的jdk序列化-->
 <bean id="jdkSerializationRedisSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/>

springboot整合Redis

1、添加依賴

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

2、配置application.yml

3、注入模板對(duì)象

@RunWith(SpringRunner.class)
@SpringBootTest
class SpringbootRedisApplicationTests {

 @Autowired
 private RedisTemplate redisTemplate;

 @PostConstruct
 public void init(){
  //配置String類型的key value序列化方式
  redisTemplate.setStringSerializer(new StringRedisSerializer());
  redisTemplate.setValueSerializer(new StringRedisSerializer());
 }

 @Test
 void contextLoads() {
  redisTemplate.opsForValue().set("age",12);
  Object age = redisTemplate.opsForValue().get("age");
  System.out.println(age);
  System.out.println("操作成功");
 }

 //獲取幾種數(shù)據(jù)結(jié)構(gòu)的對(duì)象
 @Test
 public void getRedisType(){
  //1、操作字符串?dāng)?shù)據(jù)類型
  redisTemplate.opsForValue();
  //2、操作hash的數(shù)據(jù)類型
  redisTemplate.opsForHash();
  //3、操作List的數(shù)據(jù)類型
  redisTemplate.opsForList();
  //4、操作Set的數(shù)據(jù)類型
  redisTemplate.opsForSet();
  //5、操作hSet的數(shù)據(jù)類型
  redisTemplate.opsForZSet();
  //6、操作基數(shù)的數(shù)據(jù)類型
  redisTemplate.opsForHyperLogLog();
 }
}

注意:不能在yml配置文件中配置自定義序列化,可以在springboot啟動(dòng)類或者測(cè)試類中,通過(guò)@PostConstruct注解來(lái)觸發(fā)執(zhí)行方法,從而達(dá)到配置自定義序列化的效果。

補(bǔ)充:

1.@PostConstruct說(shuō)明
被@PostConstruct修飾的方法會(huì)在服務(wù)器加載Servlet的時(shí)候運(yùn)行,并且只會(huì)被服務(wù)器調(diào)用一次,類似于Serclet的inti()方法。被@PostConstruct修飾的方法會(huì)在構(gòu)造函數(shù)之后,init()方法之前運(yùn)行。
2.@PreDestroy說(shuō)明
被@PreDestroy修飾的方法會(huì)在服務(wù)器卸載Servlet的時(shí)候運(yùn)行,并且只會(huì)被服務(wù)器調(diào)用一次,類似于Servlet的destroy()方法。被@PreDestroy修飾的方法會(huì)在destroy()方法之后運(yùn)行,在Servlet被徹底卸載之前。

總結(jié)

1、當(dāng)項(xiàng)目報(bào)以下錯(cuò)誤:Caused by: redis.clients.jedis.exceptions.JedisDataException: ERR Client sent AUTH, but no password is set
報(bào)錯(cuò)的原因:是redis服務(wù)沒(méi)設(shè)置密碼,而項(xiàng)目配置文件中寫了有redis密碼
解決方案:
1)把項(xiàng)目配置文件中的密碼password設(shè)置為空或者不設(shè)置。
2)設(shè)置redis服務(wù)密碼
——可通過(guò)直接修改redis.conf配置文件中的requirepass屬性方式,如果修改不生效,可通過(guò)命令方式修改,進(jìn)入redis的客戶端

redis 127.0.0.1:6379> CONFIG SET requirepass “root”
OK
redis 127.0.0.1:6379> AUTH root
Ok

然后重啟項(xiàng)目就可以連接本機(jī)的redis服務(wù)了。

以上就是關(guān)于詳解Java、Spring和Springboot整合Redis數(shù)據(jù)庫(kù)的具體方法的全部?jī)?nèi)容,想要了解更多詳解Java、Spring和Springboot整合Redis數(shù)據(jù)庫(kù)的其他內(nèi)容搜索W3Cschool以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持!


0 人點(diǎn)贊