JAVA连接redis实现存取数据
1、导入依赖
< dependency>
< groupId> org.springframework.boot</ groupId>
< artifactId> spring-boot-starter-data-redis</ artifactId>
</ dependency>
< dependency>
< groupId> org.springframework.session</ groupId>
< artifactId> spring-session-data-redis</ artifactId>
</ dependency>
< dependency>
< groupId> org.apache.commons</ groupId>
< artifactId> commons-pool2</ artifactId>
</ dependency>
2、配置文件application.yml
spring :
redis :
host : 主机地址
port : 主机redis端口号
lettuce :
pool :
max-active : 8
max-wait : -1
max-idle : 8
min-idle : 0
password : 连接密码
3、redis配置RedisConfig.java
import org. springframework. cache. annotation. EnableCaching;
import org. springframework. context. annotation. Bean;
import org. springframework. context. annotation. Configuration;
import org. springframework. data. redis. connection. RedisConnectionFactory;
import org. springframework. data. redis. core. RedisTemplate;
import org. springframework. data. redis. serializer. Jackson2JsonRedisSerializer;
import org. springframework. data. redis. serializer. StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
RedisTemplate< String, Object> redisTemplate ( RedisConnectionFactory redisConnectionFactory) {
RedisTemplate< String, Object> redisTemplate = new RedisTemplate < > ( ) ;
redisTemplate. setConnectionFactory ( redisConnectionFactory) ;
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer ( Object. class ) ;
redisTemplate. setValueSerializer ( jackson2JsonRedisSerializer) ;
redisTemplate. setKeySerializer ( new StringRedisSerializer ( ) ) ;
redisTemplate. setHashKeySerializer ( new StringRedisSerializer ( ) ) ;
redisTemplate. afterPropertiesSet ( ) ;
return redisTemplate;
}
}
4、测试代码
增删改查:
@RunWith ( SpringRunner. class )
@SpringBootTest
public class RedisTests {
@Autowired
RedisTemplate redisTemplate;
@Test
public void setKeyValue ( ) {
ValueOperations< Serializable, Object> operations= redisTemplate. opsForValue ( ) ;
operations. set ( key, value) ;
boolean b = redisTemplate. expire ( key, timeout, timeUnit) ;
System. out. println ( b) ;
}
@Test
public void deleteByKey ( ) {
ValueOperations< Serializable, Object> operations= redisTemplate. opsForValue ( ) ;
boolean b= redisTemplate. delete ( "name123" ) ;
System. out. println ( b) ;
}
@Test
public void searchByKey ( ) {
ValueOperations< Serializable, Object> operations= redisTemplate. opsForValue ( ) ;
String str= ( String) operations. get ( "name123" ) ;
System. out. println ( str) ;
}
}