目錄
一、Jedis
二、Lettuce
三、一個Demo
Java集成Redis主要有3個方案:Jedis、Lettuce和Redisson。
其中,Jedis、Lettuce側重于單例Redis,而Redisson側重于分布式服務。
項目資源在文末
一、Jedis
1、創建SpringBoot項目
2、引入依賴
其中,jedis是所需要的依賴,lombok是為了方便后續配置
<dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></dependency>
3、 配置yml
#redis配置--jedis版
jedis:pool:#redis服務器的IPhost: localhost#redis服務器的Portport: 6379#數據庫密碼password:#連接超時時間timeout: 7200#最大活動對象數maxTotall: 100#最大能夠保持idel狀態的對象數maxIdle: 100#最小能夠保持idel狀態的對象數minIdle: 50#當池內沒有返回對象時,最大等待時間maxWaitMillis: 10000#當調用borrow Object方法時,是否進行有效性檢查testOnBorrow: true#當調用return Object方法時,是否進行有效性檢查testOnReturn: true#“空閑鏈接”檢測線程,檢測的周期,毫秒數。如果為負值,表示不運行“檢測線程”。默認為-1.timeBetweenEvictionRunsMillis: 30000#向調用者輸出“鏈接”對象時,是否檢測它的空閑超時;testWhileIdle: true# 對于“空閑鏈接”檢測線程而言,每次檢測的鏈接資源的個數。默認為3.numTestsPerEvictionRun: 50
4、導入配置文件和加載配置類
導入配置文件:JedisProperties,導入yml文件內容
加載配置類:JedisConfig,加載JedisProperties內容
①JedisProperties
package com.example.redis_java.config;import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;@Component
@ConfigurationProperties(prefix = "jedis.pool")
@Getter
@Setter
public class JedisProperties {private int maxTotall;private int maxIdle;private int minIdle;private int maxWaitMillis;private boolean testOnBorrow;private boolean testOnReturn;private int timeBetweenEvictionRunsMillis;private boolean testWhileIdle;private int numTestsPerEvictionRun;private String host;private String password;private int port;private int timeout;
}
②JedisConfig
說明:如果SpringBoot是2.x版本,JedisConfig請使用注釋掉的兩行代碼而不是它們對應的上面的代碼
package com.example.redis_java.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;import java.time.Duration;@Configuration
public class JedisConfig {/*** jedis連接池** @param jedisProperties* @return*/@Beanpublic JedisPool jedisPool(JedisProperties jedisProperties) {JedisPoolConfig config = new JedisPoolConfig();config.setMaxTotal(jedisProperties.getMaxTotall());config.setMaxIdle(jedisProperties.getMaxIdle());config.setMinIdle(jedisProperties.getMinIdle());config.setMaxWait(Duration.ofMillis(jedisProperties.getMaxWaitMillis()));// config.setMaxWaitMillis(jedisProperties.getMaxWaitMillis());config.setTestOnBorrow(jedisProperties.isTestOnBorrow());config.setTestOnReturn(jedisProperties.isTestOnReturn());config.setTimeBetweenEvictionRuns(Duration.ofMillis(jedisProperties.getTimeBetweenEvictionRunsMillis()));// config.setTimeBetweenEvictionRunsMillis(jedisProperties.getTimeBetweenEvictionRunsMillis());config.setTestWhileIdle(jedisProperties.isTestWhileIdle());config.setNumTestsPerEvictionRun(jedisProperties.getNumTestsPerEvictionRun());if (StringUtils.hasText(jedisProperties.getPassword())) {return new JedisPool(config, jedisProperties.getHost(), jedisProperties.getPort(), jedisProperties.getTimeout(), jedisProperties.getPassword());}return new JedisPool(config, jedisProperties.getHost(), jedisProperties.getPort(), jedisProperties.getTimeout());}
}
③項目結構
5、測試
①測試前
②測試類
package com.example.redis_java;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;@SpringBootTest
public class JedisTest {@Autowiredprivate JedisPool jedisPool;@Testpublic void testConnection() {System.out.println(jedisPool);Jedis jedis = jedisPool.getResource();jedis.set("name", "Trxcx");System.out.println(jedis.get("name"));jedis.sadd("mySet", "a", "b", "d");System.out.println(jedis.smembers("mySet"));// jedis的方法名就是redis的命令jedis.close();}
}
③項目結構
??
④運行測試類
⑤測試后
說明:jedis的方法名就是redis的命令。如sadd、smembers。
二、Lettuce
Lettuce配置比較簡單,這里直接在上一個項目的基礎上進行配置,新項目配置Lettuce方法一致。
1、引入依賴
<!--Lettuce依賴--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency>
2、配置yml
如果有密碼,設置對應的密碼。
spring:redis:host: 127.0.0.1port: 6379# password: admin
3、測試
①編寫測試類
package com.example.redis_java;import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;@SpringBootTest
public class LettureTest {@Autowiredprivate StringRedisTemplate template;// 約定:// 操作redis的key是字符串// value是字符串類型或字符串類型元素@Testpublic void testRedis() {template.opsForValue().set("name", "Trxcx");System.out.println(template.opsForValue().get("name"));template.opsForSet().add("Games","RDR2","CS2","ACOd");System.out.println(template.opsForSet().members("Games"));// 操作string// template.opsForValue().xx();// 操作hash// template.opsForHash().xx();// 操作list// template.opsForList().xx();// 操作set// template.opsForSet().xx();// 操作zset// template.opsForZSet().xx();// spring-data-redis方法是redis命令全稱// template.opsForList().rightPush() //rpush// 全局命令在template類上// template.keys("*");}
}
②項目結構
③運行測試類
4、說明:
①Lettuce使用StringRedisTemplate的一個對象完成對Redis的操作,不存在像Jedis那樣獲取Redis資源使用完再關閉的情況。
②Lettuce通過opsForxxx完成對不同value類型的操作,例如
- opsForValue()是操作String類型的
- opsForHash()是操作Hash類型的
- opsForList()是操作List類型的
- opsForSet()是操作Set類型的
- opsForZSet()是操作Zset類型的
③Lettuce的方法名是Redis命令的全稱
例如:template.opsForList().rightPush(),對應Redis中的rpush命令
④全局命令作用在StringRedisTemplate對象上
例如:template.keys("*");
三、一個Demo
這個demo實現了每次刷新或者訪問網頁時,閱讀量+1的效果。
啟動SpringBoot項目后,訪問http://localhost:8080/detail.html,每次刷新頁面閱讀量+1。?
項目資源鏈接:
1、【免費】Redis-Java.zip資源-CSDN文庫
2、【免費】RedisDemo.zip資源-CSDN文庫?