十一、Spring Boot整合Redis(一)

Spring Boot整合Redis

   1. SpringBoot+单例Redis

1)引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

(2)添加配置文件

 

# Redis数据库索引(默认为0)
spring.redis.database=
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379 
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

添加 cache 的配置类

  (@EnableCaching来开启缓存)

@Configuration
@EnableCaching

public class RedisConfig extends CachingConfigurerSupport {

   
@Bean
   
public KeyGenerator keyGenerator() {
       
return new KeyGenerator() {
           
@Override
           
public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb =
new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
               
for (Object obj : params) {
                    sb.append(obj.toString());
                }
               
return sb.toString();
            }
        };
    }
}

(4)可以直接使用

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {
   
@Autowired
   
private StringRedisTemplate stringRedisTemplate;
   
@Autowired
   
private RedisTemplate redisTemplate;

   
@Test
   
public void test() throws Exception {
       
stringRedisTemplate.opsForValue().set("aaa", "111");
        Assert.assertEquals(
"111", stringRedisTemplate.opsForValue().get("aaa"));
    }

   
@Test
   
public void testObj() throws Exception {
        SecurityProperties.User user=
new SecurityProperties.User("[email protected]", "admin", "aa123456", "admin","123");
        ValueOperations<String, SecurityProperties.User> operations=
redisTemplate.opsForValue();
        operations.set(
"com.neox", user);
        operations.set(
"com.neo.f", user,1, TimeUnit.SECONDS);
        Thread.sleep(
1000);
       
//redisTemplate.delete("com.neo.f");
       
boolean exists=redisTemplate.hasKey("com.neo.f");
       
if(exists){
            System.
out.println("exists is true");
        }
else{
            System.
out.println("exists is false");
        }


    }
}

扫描二维码关注公众号,回复: 11091574 查看本文章

 

 

 

发布了49 篇原创文章 · 获赞 31 · 访问量 2877

猜你喜欢

转载自blog.csdn.net/cjy_lean/article/details/105543177