Redis大杂烩

栏目: 数据库 · 发布时间: 5年前

内容简介:添加依赖
brew install redis
redis-server

Redis在SpringBoot项目中的配置

添加依赖 spring-boot-starter-data-redis 即可

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

Java示例代码

package bj.redis;

import io.vavr.control.Try;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * Created by BaiJiFeiLong@gmail.com at 2018/12/13 上午9:51
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class RedisApp implements ApplicationListener<ApplicationReadyEvent> {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static void main(String[] args) {
        SpringApplication.run(RedisApp.class, args);
    }

    @Override
    public void onApplicationEvent(@NotNull ApplicationReadyEvent event) {
        Try.run(this::_onReady).getOrElseThrow((Function<Throwable, RuntimeException>) RuntimeException::new);
    }

    private void _onReady() throws InterruptedException {
        stringRedisTemplate.opsForValue().set("GMail", "Google", 1, TimeUnit.SECONDS);
        System.out.println("[After cached] GMail: " + stringRedisTemplate.opsForValue().get("GMail"));
        Thread.sleep(1000);
        System.out.println("[After timeout] GMail: " + stringRedisTemplate.opsForValue().get("GMail"));
    }
}

控制台输出

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

2018-12-13 10:15:58.921  INFO 44761 --- [           main] bj.redis.RedisApp                        : Starting RedisApp on MacBook-Air-2.local with PID 44761 (/Users/yuchao/temp/java/hellomaven/target/classes started by yuchao in /Users/yuchao/temp/java/hellomaven)
2018-12-13 10:15:58.936  INFO 44761 --- [           main] bj.redis.RedisApp                        : No active profile set, falling back to default profiles: default
2018-12-13 10:16:00.818  INFO 44761 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2018-12-13 10:16:00.821  INFO 44761 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2018-12-13 10:16:00.859  INFO 44761 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 17ms. Found 0 repository interfaces.
2018-12-13 10:16:02.564  INFO 44761 --- [           main] bj.redis.RedisApp                        : Started RedisApp in 4.561 seconds (JVM running for 6.042)
2018-12-13 10:16:02.692  INFO 44761 --- [           main] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2018-12-13 10:16:02.809  INFO 44761 --- [           main] io.lettuce.core.KqueueProvider           : Starting with kqueue library
[After cached] GMail: Google
[After timeout] GMail: null

Redis与SpringCache

示例代码

package bj.redis;

import io.vavr.collection.HashMap;
import io.vavr.control.Try;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * Created by BaiJiFeiLong@Gmail.com at 2018/12/13 上午9:51
 */
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableCaching
public class RedisApp implements ApplicationListener<ApplicationReadyEvent> {


    public static void main(String[] args) {
        SpringApplication.run(RedisApp.class, args);
    }

    @Override
    public void onApplicationEvent(@NotNull ApplicationReadyEvent event) {
        Try.run(this::_onReady).getOrElseThrow((Function<Throwable, RuntimeException>) RuntimeException::new);
    }

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private Inner inner;

    private void _onReady() throws InterruptedException {
        stringRedisTemplate.opsForValue().set("a", "b");
        System.out.println("TTL of a: " + stringRedisTemplate.getExpire("a", TimeUnit.MILLISECONDS));
        System.out.println("[Before cache] Owner of Gmail: " + inner.owner("Gmail"));
        System.out.println("[After cache] Owner of Gmail: " + inner.owner("Gmail"));
        System.out.println("Expire millis: " + stringRedisTemplate.getExpire("alpha::owner::Gmail", TimeUnit.MILLISECONDS));
        System.out.println("Keys: " + stringRedisTemplate.keys("*"));
        Thread.sleep(100);
        System.out.println("[After expire] Owner of Gmail: " + inner.owner("Gmail"));
        System.out.println("Raw: " + stringRedisTemplate.opsForValue().get("alpha::owner::Gmail"));
    }

    @Component
    static class Inner {
        @Cacheable("alpha::owner")
        public String owner(String product) {
            System.out.println("Fetching...");
            return HashMap.of("Gmail", "Google").getOrElse(product, null);
        }
    }

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        return RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                .entryTtl(Duration.ofMillis(100));
    }
}

控制台输出

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.0.RELEASE)

2018-12-13 11:48:16.788  INFO 45720 --- [           main] bj.redis.RedisApp                        : Starting RedisApp on MacBook-Air-2.local with PID 45720 (/Users/yuchao/temp/java/hellomaven/target/classes started by yuchao in /Users/yuchao/temp/java/hellomaven)
2018-12-13 11:48:16.810  INFO 45720 --- [           main] bj.redis.RedisApp                        : No active profile set, falling back to default profiles: default
2018-12-13 11:48:18.079  INFO 45720 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2018-12-13 11:48:18.082  INFO 45720 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2018-12-13 11:48:18.117  INFO 45720 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 16ms. Found 0 repository interfaces.
2018-12-13 11:48:19.243  INFO 45720 --- [           main] bj.redis.RedisApp                        : Started RedisApp in 3.305 seconds (JVM running for 4.684)
2018-12-13 11:48:19.484  INFO 45720 --- [           main] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2018-12-13 11:48:19.512  INFO 45720 --- [           main] io.lettuce.core.KqueueProvider           : Starting with kqueue library
TTL of a: -1
Fetching...
[Before cache] Owner of Gmail: Google
[After cache] Owner of Gmail: Google
Expire millis: 54
Keys: [a, alpha::owner::Gmail]
Fetching...
[After expire] Owner of Gmail: Google
Raw: "Google"

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

未来是湿的

未来是湿的

[美] 克莱·舍基 / 胡泳、沈满琳 / 中国人民大学出版社 / 2009-5 / 39.80

一位妇女丢掉了手机,但征召了一群志愿者将其从盗窃者手中夺回。一个旅客在乘坐飞机时领受恶劣服务,她通过自己的博客发动了一场全民运动。在伦敦地铁爆炸案和印度洋海啸中,公民们用可拍照手机提供了比摄影记者更完备的记录。世界上最大的百科全书是由管理甚少的参与者们撰写的…… 不论在何处,你都能看见人们走到一起彼此分享,共同工作,或是发起某种公共行动。一部集众人之力的百科全书、一个丢失手机的传奇,这些事情......一起来看看 《未来是湿的》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换