Spring Boot Sample 021之spring-boot-data-redis-jedis
一、环境
- Idea 2020.1
- JDK 1.8
- maven
二、目的
spring boot 通过Jedis整合redis
三、步骤
3.1、点击File -> New Project -> Spring Initializer,点击next
3.2、在对应地方修改自己的项目信息
3.3、选择Web依赖,选中Spring Web、Spring Boot Redis。可以选择Spring Boot版本,本次默认为2.2.7,点击Next
3.4、项目结构
四、添加文件
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>org.ouyushan</groupId> <artifactId>spring-boot-data-redis-jedis</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-data-redis-jedis</name> <description>Jedis project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <exclusions> <exclusion> <groupId>io.lettuce</groupId> <artifactId>lettuce-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
application.properties文件
######## REDIS ######## # Redis数据库索引(默认为0) spring.redis.database=0 # Redis服务器地址 spring.redis.host=127.0.0.1 # Redis服务器连接端口 spring.redis.port=6379 # Redis服务器连接密码(默认为空) spring.redis.password= # 连接超时时间(毫秒) spring.redis.timeout=0 # 连接池最大连接数(使用负值表示没有限制) 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
JedisRedisConfig.java
package org.ouyushan.springboot.data.redis.jedis.config; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisPassword; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.jedis.JedisClientConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig; import java.time.Duration; /** * @Description: 利用连接池管理redis连接 * @Author: ouyushan * @Email: ouyushan@hotmail.com * @Date: 2020/5/9 11:20 */ @Configuration @EnableCaching public class JedisRedisConfig { @Value("${spring.redis.database}") private int database; @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.password}") private String password; @Value("${spring.redis.timeout}") private int timeout; @Value("${spring.redis.jedis.pool.max-active}") private int maxActive; @Value("${spring.redis.jedis.pool.max-wait}") private long maxWaitMillis; @Value("${spring.redis.jedis.pool.max-idle}") private int maxIdle; @Value("${spring.redis.jedis.pool.min-idle}") private int minIdle; /** * 连接池配置信息 */ @Bean public JedisPoolConfig jedisPoolConfig() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // 最大连接数 jedisPoolConfig.setMaxTotal(maxActive); // 当池内没有可用连接时,最大等待时间 jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); // 最大空闲连接数 jedisPoolConfig.setMinIdle(maxIdle); // 最小空闲连接数 jedisPoolConfig.setMinIdle(minIdle); // 其他属性可以自行添加 return jedisPoolConfig; } /** * Jedis 连接 * * @param jedisPoolConfig * @return */ @Bean public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) { JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder().usePooling() .poolConfig(jedisPoolConfig).and().readTimeout(Duration.ofMillis(timeout)).build(); RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(); redisStandaloneConfiguration.setHostName(host); redisStandaloneConfiguration.setPort(port); redisStandaloneConfiguration.setDatabase(database); redisStandaloneConfiguration.setPassword(RedisPassword.of(password)); return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration); } // 缓存管理器 @Bean public RedisCacheManager cacheManager(RedisConnectionFactory jedisConnectionFactory) { RedisCacheManager redisCacheManager = RedisCacheManager.builder(jedisConnectionFactory).build(); return redisCacheManager; } @Bean public RedisTemplate<Object, Object> redisTemplate(JedisConnectionFactory redisConnectionFactory) { RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // key序列化 redisTemplate.setKeySerializer(new StringRedisSerializer()); // 使用Jackson ,将对象序列化为JSON Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); //json 转对象类,不设置默认的会将json转成hashmap 报错:java.util.LinkedHashMap cannot be cast to XX ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
UserInfo.java
package org.ouyushan.springboot.data.redis.jedis.entity; import java.io.Serializable; /** * @Description: * @Author: ouyushan * @Email: ouyushan@hotmail.com * @Date: 2020/5/9 14:03 */ public class UserInfo implements Serializable { private static final long serialVersionUID = -6264728881593912971L; private Long id; private String userName; private String password; private int age; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "UserInfo{" + "id=" + id + ", userName='" + userName + '\'' + ", password='" + password + '\'' + ", age=" + age + '}'; } }
五、测试
运行以下测试用例验证String、Object、List以及Map在redis中的使用
SpringBootDataRedisJedisApplicationTests .java
package org.ouyushan.springboot.data.redis.jedis; import org.junit.jupiter.api.Test; import org.ouyushan.springboot.data.redis.jedis.entity.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import java.util.*; import static org.assertj.core.api.Assertions.assertThat; @SpringBootTest class SpringBootDataRedisJedisApplicationTests { @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; @Test public void testStringRedisTemplateForObject() { stringRedisTemplate.opsForValue().set("keyString", "valueString"); String value = stringRedisTemplate.opsForValue().get("keyString"); System.out.println(value); assertThat(value).isEqualTo("valueString"); } @Test public void testRedisTemplateForObject() { UserInfo userInfo = new UserInfo(); userInfo.setAge(24); userInfo.setId(1L); userInfo.setUserName("username"); userInfo.setPassword("password"); redisTemplate.opsForValue().set("object", userInfo); UserInfo userInfoFromRedis = (UserInfo) redisTemplate.opsForValue().get("object"); System.out.println(userInfoFromRedis); } @Test public void testRedisTemplateForList() { UserInfo userInfo1 = new UserInfo(); userInfo1.setAge(11); userInfo1.setId(1L); userInfo1.setUserName("username"); userInfo1.setPassword("password"); UserInfo userInfo2 = new UserInfo(); userInfo2.setAge(21); userInfo2.setId(2L); userInfo2.setUserName("username"); userInfo2.setPassword("password"); List<UserInfo> list = new ArrayList<>(); list.add(userInfo1); list.add(userInfo2); redisTemplate.opsForValue().set("list", list); List<UserInfo> userInfoFromRedis = (List) redisTemplate.opsForValue().get("list"); System.out.println(userInfoFromRedis); } @Test public void testRedisTemplateForMap() { UserInfo userInfo1 = new UserInfo(); userInfo1.setAge(11); userInfo1.setId(1L); userInfo1.setUserName("username"); userInfo1.setPassword("password"); UserInfo userInfo2 = new UserInfo(); userInfo2.setAge(22); userInfo2.setId(2L); userInfo2.setUserName("username"); userInfo2.setPassword("password"); Map<String, UserInfo> map = new HashMap<>(); map.put("userInfo1", userInfo1); map.put("userInfo2", userInfo2); redisTemplate.opsForValue().set("map", map); Map<String, UserInfo> userInfoFromRedis = (Map<String, UserInfo>) redisTemplate.opsForValue().get("map"); System.out.println(userInfoFromRedis); } }