介绍:在lettuce那一篇里面写了用lettuce连接数据库,并且操作redis数据库
结构图:
1.依赖包
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.1.9.RELEASE</version> </dependency>
2.SpringData连接redis数据库
• 先创建一个src/main/profiles/dev/config/redis.properties配置文件,dev为源文件夹。在此配置文件中配置所有与redis有关的属性。
redis.host=redis-server//redis数据库连接的主机名称或ip地址 redis.port=6379 //连接端口 redis.auth=hellolee //认证信息 redis.database=0 //数据库的索引编号 redis.pool.maxTotal=10 //连接池最大的总连接数量 redis.pool.maxIdle=5 //连接池维持的最大连接数量 redis.pool.minIdle=3 //连接池维持的最小的连接数量 redis.pool.testOnBorrow=true //所有的连接测试后返回
• 在src/main/resources/spring/spring-base.xml配置文件中添加扫描redis.properties所在的包
<context:component-scan base-package="com.yootk.redis.config"/>
•编写配置类SpringDataRedisConfig.java
package com.yootk.redis.config; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; 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.lettuce.LettuceClientConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration; @Configuration @PropertySource("classpath:config/redis.properties") public class SpringDataRedisConfig { @Bean("redisConfiguration") public RedisStandaloneConfiguration getRedisConfiguration( @Value("${redis.host}") String hostName , @Value("${redis.port}") int port, @Value("${redis.auth}") String password, @Value("${redis.database}") int database ) { RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration() ; configuration.setHostName(hostName); // 设置Redis主机名称 configuration.setPort(port); // 设置Redis的访问端口 configuration.setPassword(RedisPassword.of(password)); // 设置密码 configuration.setDatabase(database); // 设置数据库索引 return configuration ; } @Bean("objectPoolConfig") public GenericObjectPoolConfig getObjectPoolConfig( @Value("${redis.pool.maxTotal}") int maxTotal , @Value("${redis.pool.maxIdle}") int maxIdle , @Value("${redis.pool.minIdle}") int minIdle , @Value("${redis.pool.testOnBorrow}") boolean testOnBorrow ) { GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig() ; poolConfig.setMaxTotal(maxTotal); poolConfig.setMaxIdle(maxIdle); poolConfig.setMinIdle(minIdle); poolConfig.setTestOnBorrow(testOnBorrow); return poolConfig ; } @Bean("lettuceClientConfiguration") public LettuceClientConfiguration getLettuceClientConfiguration( @Autowired GenericObjectPoolConfig poolConfig ) { // 创建Lettuce组件的连接池客户端配置对象 return LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build() ; } @Bean("redisConnectionFactory")//相当于在这例实例化了RedisConnectionFactory类的实例化对象,前面双引号中的内容就是对象,
//一旦在其他地方自动注入此对象的时候,此方法便自动执行,所以执行此方法就相当于执行了一个构造方法。 public RedisConnectionFactory getConnectionFactory( @Autowired RedisStandaloneConfiguration redisConfiguration , @Autowired LettuceClientConfiguration lettuceClientConfiguration ) { LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(redisConfiguration,lettuceClientConfiguration) ; return connectionFactory ; } }
测试当前的Redis是否可以正常连接,编写测试类
package com.yootk.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration(locations = {"classpath:spring/*.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class TestRedisConnection { @Autowired private RedisConnectionFactory redisConnectionFactory ; @Test public void testRedis() { System.out.println(this.redisConnectionFactory); // 输出连接工厂实例 this.redisConnectionFactory.getConnection().flushDb(); // 清空数据库 } }
3.RedisTemplate
• 修改配置类SpringDataRedisConfig.java,添加两个方法
@Bean("stringRedisTemplate") public RedisTemplate getStringRedisTempalate( @Autowired RedisConnectionFactory connectionFactory ) { StringRedisTemplate redisTemplate = new StringRedisTemplate() ; redisTemplate.setConnectionFactory(connectionFactory); return redisTemplate ; } @Bean("redisTemplate") public RedisTemplate getRedisTempalate( @Autowired RedisConnectionFactory connectionFactory ) { RedisTemplate<String,String> redisTemplate = new RedisTemplate<>() ; redisTemplate.setConnectionFactory(connectionFactory); return redisTemplate ; }
• 测试StringRedisTemplate
package com.yootk.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.HashMap; import java.util.Map; import java.util.Set; @ContextConfiguration(locations = {"classpath:spring/*.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class TestRedisTemplateBase { @Autowired private RedisTemplate<String, String> stringRedisTemplate; @Test public void testString() { for (int x = 0; x < 10; x++) { this.stringRedisTemplate.opsForValue().set("msg - " + x, "Hello - " + x); } } @Test public void testHash() { Map<String, String> map = new HashMap<>(); map.put("name", "可爱的小李老师"); map.put("age", String.valueOf(16)); map.put("salary", String.valueOf(1.1)); this.stringRedisTemplate.opsForHash().putAll("member-lee", map); System.out.println(this.stringRedisTemplate.opsForHash().get("member-lee","name")); } @Test public void testKeys() { Set<String> keys = this.stringRedisTemplate.keys("msg - *"); System.out.println("【所有的key】" + keys); } }
• 测试RedisTemplate
package com.yootk.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration(locations = {"classpath:spring/*.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class TestRedisTemplate { @Autowired private RedisTemplate<String, String> redisTemplate; @Test public void testString() { this.redisTemplate.execute(new RedisCallback<Object>() { // Redis回调 @Override public Object doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); // 清空数据库 return "ok"; } }) ; for (int x = 0; x < 10; x++) { this.redisTemplate.opsForValue().set("message-" + x, "Hello - " + x); } } @Test public void testGet() { System.err.println("【获取数据】" + this.redisTemplate.opsForValue().get("message-3")); } }
4. 对象序列化存储:在redis数据库中存放类的对象,强调:对象对应的类一定要实现Serializable接口。
RedisTemplate与StringRedisTemplate的区别:StringRedisTemplate是设置了一系列字符串序列化处理的RedisTemplate。
在SpringDataRedis里面对象序列化处理操作有两种方式:基于JDK的序列化处理机制,基于JSON的序列化处理机制。如果哦代码通过java实现,并且充分考虑到性能则使用JDK的机制,如果考虑到数据的通用性则使用JSON机制。
• 使用JDK机制存储对象,修改配置类SpringDataRedisConfig.java
@Bean("redisTemplate")//将原来的getRedisTempalate方法改成现在这个 public RedisTemplate getRedisTempalate( @Autowired RedisConnectionFactory connectionFactory ) { RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>() ; redisTemplate.setConnectionFactory(connectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储 redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); // 保存的value为对象 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储 redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); // 保存的value为对象 return redisTemplate ; }
• 使用JSON机制存储对象,修改配置类SpringDataRedisConfig.java
@Bean("redisTemplate")//将原来的getRedisTempalate方法改成现在这个 public RedisTemplate getRedisTempalate( @Autowired RedisConnectionFactory connectionFactory ) { RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>() ; redisTemplate.setConnectionFactory(connectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储 redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(Object.class)); // 保存的value为对象 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储 redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer(Object.class)); // 保存的value为对象 return redisTemplate ; }
5.Pipeline流水线(详情见笔记)