Redis 在 Java Web 主要有两个应用场景:
- 存储 缓存 用的数据;
- 需要高速读/写的场合使用它快速读/写;
使用 Redis 作为缓存的读取逻辑如下图所示:
使用 Redis 来应对高并发需求的场合如下图所示:
在 Java 中使用 Redis
引入jedis-2.9.0.jar、commons-pool2-2.6.0.jar等开发包
public static void testRedis() {
Jedis jedis = new Jedis("localhost", 6379, 100000);
int i = 0;
try {
long start = System.currentTimeMillis();// 开始毫秒数
while (true) {
long end = System.currentTimeMillis();
if (end - start >= 1000) {// 当大于等于1000毫秒(相当于1秒)时,结束操作
break;
}
i++;
jedis.set("test" + i, i + "");
}
} finally {// 关闭连接
jedis.close();
}
// 打印1秒内对Redis的操作次数
System.out.println("redis每秒操作:" + i + "次");
}
public static void testRedisByPools() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
// 最大空闲数
poolConfig.setMaxIdle(50);
// 最大连接数
poolConfig.setMaxTotal(100);
// 最大等待毫秒数
poolConfig.setMaxWaitMillis(20000);
// 使用配置创建连接池
JedisPool pool = new JedisPool(poolConfig,"localhost");
// 从连接池中获取单个连接
Jedis jedis = pool.getResource();
// 如果需要密码
//jedis.auth("password");
int i = 0;
try {
long start = System.currentTimeMillis();// 开始毫秒数
while (true) {
long end = System.currentTimeMillis();
if (end - start >= 1000) {// 当大于等于1000毫秒(相当于1秒)时,结束操作
break;
}
i++;
jedis.set("test" + i, i + "");
}
} finally {// 关闭连接
jedis.close();
pool.close();
}
// 打印1秒内对Redis的操作次数
System.out.println("redis每秒操作:" + i + "次");
}
在 Spring 中使用 Redis
引入jedis-2.9.0.jar、commons-pool2-2.6.0.jar、spring-data-redis-1.8.4.RELEASE.jar、
spring-data-commons-1.8.4.RELEASE.jar以及springframe 4.3.20核心包等jar。
一定要注意版本匹配,不然异常满天飞...
<!-- spring 配置文件 applicationContext.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<!-- 由 Spring容器创建该类的实例对象 -->
<bean id="annotationPropertyConfigurerRedis"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
<!-- redis连接池 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!--最大空闲数-->
<property name="maxIdle" value="50"/>
<!--最大连接数-->
<property name="maxTotal" value="100"/>
<!--最大等待时间-->
<property name="maxWaitMillis" value="20000"/>
</bean>
<!-- 连接池配置工厂模型 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<!--Redis服务地址-->
<property name="hostName" value="localhost"/>
<!--端口号-->
<property name="port" value="6379"/>
<!--如果有密码则需要配置密码-->
<!--<property name="password" value="password"/>-->
<!--连接池配置-->
<property name="poolConfig" ref="poolConfig"/>
<!-- 超时时间 默认2000-->
<property name="timeout" value="6000" />
<!-- usePool:是否使用连接池 -->
<property name="usePool" value="true"/>
</bean>
<!-- 对象序列化存入Redis内存 反序列化还原对象-->
<bean id="redisTemplate"
class="org.springframework.data.redis.core.RedisTemplate"
p:connection-factory-ref="connectionFactory"/>
<!--
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
</property>
<property name="enableTransactionSupport" value="true"></property>
</bean>
-->
<!--自定义redis工具类,在需要缓存的地方注入此类
<bean id="redisService" class="com.cff.springwork.redis.service.RedisService">
<property name="redisTemplate" ref="redisTemplate" />
</bean>
-->
</beans>
public static void testRedisbySpring() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
@SuppressWarnings("unchecked")
RedisTemplate<String, Object> redisTemplate = context.getBean(RedisTemplate.class);
redisTemplate.opsForValue().set("testa","testa value");
System.out.println(redisTemplate.opsForValue().get("testa"));
redisTemplate.opsForHash().put("hashtest", "hashkey", "hashvalue");
System.out.println(redisTemplate.opsForHash().get("hashtest", "hashkey"));
redisTemplate.opsForList().leftPush("listtest", "listitem");
System.out.println(redisTemplate.opsForList().size("listtest"));
redisTemplate.opsForSet().add("settest", "setvalue");
System.out.println(redisTemplate.opsForSet().pop("settest"));
Student student = new Student();
student.setName("三颗心脏");
student.setAge(21);
redisTemplate.opsForValue().set("student_1", student);
Student student1 = (Student) redisTemplate.opsForValue().get("student_1");
student1.toString();
}
在 SpringBoot 中使用 Redis
<!-- Radis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
# application.properties
# REDIS (RedisProperties)
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=8
spring.redis.jedis.pool.min-idle=0
spring.redis.timeout=1000000
package com.example.demo;
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 RedisApplicationTests {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void test() throws Exception {
// 保存字符串
stringRedisTemplate.opsForValue().set("aaa", "111");
System.out.println("get value from redis: " + stringRedisTemplate.opsForValue().get("aaa"));
}
}
Redis详细参考如下:
Redis 安装、配置、以及各种命令参见菜鸟教程:
https://www.runoob.com/redis/redis-install.html
Redis【入门】就这一篇!
https://www.jianshu.com/p/56999f2b8e3b