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"

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

查看所有标签

猜你喜欢:

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

区块链与人工智能:数字经济新时代

区块链与人工智能:数字经济新时代

高航、俞学劢、王毛路 / 电子工业出版社 / 2018-7-23 / 80

《区块链与人工智能》是畅销书《区块链与新经济:数字货币2.0时代》全新修订升级版。本书是市场上为数不多的系统阐述区块链、人工智能技术与产业的入门级系统教程。从比特币到各类数字货币(代币),从基础原理到应用探讨,全景式呈现区块链与人工智能的发展脉络,既有历史的厚重感也有科技的未来感。本书的另一个亮点是系统整理了区块链创业地图,是一本关于区块链创业、应用、媒体的学习指南,以太坊创始人Vitalik专门......一起来看看 《区块链与人工智能:数字经济新时代》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

MD5 加密
MD5 加密

MD5 加密工具

SHA 加密
SHA 加密

SHA 加密工具