redis-demo关键代码

...
...
...
...
[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-08-01 16:02:12.648  INFO 8776 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-08-01 16:02:13.298  INFO 8776 --- [           main] c.e.redisdemo.RedisDemoApplication       : Started RedisDemoApplication in 4.7 seconds (JVM running for 8.652)
2020-08-01 16:02:13.404  INFO 8776 --- [           main] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2020-08-01 16:02:13.405  INFO 8776 --- [           main] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library
Hibernate: 
    select
        coffee0_.id as id1_0_,
        coffee0_.create_time as create_t2_0_,
        coffee0_.update_time as update_t3_0_,
        coffee0_.name as name4_0_,
        coffee0_.price as price5_0_ 
    from
        t_coffee coffee0_ 
    where
        lower(coffee0_.name)=?
2020-08-01 16:02:15.228  INFO 8776 --- [           main] c.e.redisdemo.service.CoffeeService      : Coffee Found: Optional[Coffee(super=BaseEntity(id=4, createTime=2020-08-01 16:02:11.205, updateTime=2020-08-01 16:02:11.205), name=mocha, price=CNY 30.00)]
2020-08-01 16:02:15.228  INFO 8776 --- [           main] c.e.redisdemo.service.CoffeeService      : Put coffee mocha to Redis.
2020-08-01 16:02:15.240  INFO 8776 --- [           main] c.e.redisdemo.RedisDemoApplication       : Coffee Optional[Coffee(super=BaseEntity(id=4, createTime=2020-08-01 16:02:11.205, updateTime=2020-08-01 16:02:11.205), name=mocha, price=CNY 30.00)]
2020-08-01 16:02:15.244  INFO 8776 --- [           main] c.e.redisdemo.service.CoffeeService      : Get coffee mocha from Redis.
2020-08-01 16:02:15.253  INFO 8776 --- [           main] c.e.redisdemo.service.CoffeeService      : Get coffee mocha from Redis.
2020-08-01 16:02:15.258  INFO 8776 --- [           main] c.e.redisdemo.service.CoffeeService      : Get coffee mocha from Redis.
2020-08-01 16:02:15.263  INFO 8776 --- [           main] c.e.redisdemo.service.CoffeeService      : Get coffee mocha from Redis.
2020-08-01 16:02:15.270  INFO 8776 --- [           main] c.e.redisdemo.service.CoffeeService      : Get coffee mocha from Redis.
2020-08-01 16:02:15.271  INFO 8776 --- [           main] c.e.redisdemo.RedisDemoApplication       : Value from Redis: Optional[Coffee(super=BaseEntity(id=4, createTime=2020-08-01 16:02:11.205, updateTime=2020-08-01 16:02:11.205), name=mocha, price=CNY 30.00)]
2020-08-01 16:02:15.413  INFO 8776 --- [extShutdownHook] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-08-01 16:02:15.418  INFO 8776 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-08-01 16:02:15.423  INFO 8776 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.

Process finished with exit code 0

配置文件

spring.jpa.hibernate.ddl-auto=none
spring.jpa.properties.hibernate.show_sql=true
spring.jpa.properties.hibernate.format_sql=true

management.endpoints.web.exposure.include=*

spring.redis.host=localhost
spring.redis.lettuce.pool.maxActive=5
spring.redis.lettuce.pool.maxIdle=5

初始化sql schema.sql

drop table t_coffee if exists;
drop table t_order if exists;
drop table t_order_coffee if exists;

create table t_coffee (
    id bigint auto_increment,
    create_time timestamp,
    update_time timestamp,
    name varchar(255),
    price bigint,
    primary key (id)
);

create table t_order (
    id bigint auto_increment,
    create_time timestamp,
    update_time timestamp,
    customer varchar(255),
    state integer not null,
    primary key (id)
);

create table t_order_coffee (
    coffee_order_id bigint not null,
    items_id bigint not null
);

insert into t_coffee (name, price, create_time, update_time) values ('espresso', 2000, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('latte', 2500, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('capuccino', 2500, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('mocha', 3000, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('macchiato', 3000, now(), now());

coffeeService

package com.example.redisdemo.service;

import com.example.redisdemo.model.Coffee;
import com.example.redisdemo.repository.CoffeeRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.exact;

@Slf4j
@Service
public class CoffeeService {
    private static final String CACHE = "springbucks-coffee";
    @Autowired
    private CoffeeRepository coffeeRepository;
    @Autowired
    private RedisTemplate<String, Coffee> redisTemplate;

    public List<Coffee> findAllCoffee() {
        return coffeeRepository.findAll();
    }

    public Optional<Coffee> findOneCoffee(String name) {
        HashOperations<String, String, Coffee> hashOperations = redisTemplate.opsForHash();
        if (redisTemplate.hasKey(CACHE) && hashOperations.hasKey(CACHE, name)) {
            log.info("Get coffee {} from Redis.", name);
            return Optional.of(hashOperations.get(CACHE, name));
        }
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withMatcher("name", exact().ignoreCase());
        Optional<Coffee> coffee = coffeeRepository.findOne(
                Example.of(Coffee.builder().name(name).build(), matcher));
        log.info("Coffee Found: {}", coffee);
        if (coffee.isPresent()) {
            log.info("Put coffee {} to Redis.", name);
            hashOperations.put(CACHE, name, coffee.get());
            redisTemplate.expire(CACHE, 1, TimeUnit.MINUTES);
        }
        return coffee;
    }
}

Main

package com.example.redisdemo;

import com.example.redisdemo.model.Coffee;
import com.example.redisdemo.service.CoffeeService;
import io.lettuce.core.ReadFrom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.Optional;

/**
 * 这是结合JPA REDIS在springboot中使用缓存的demo
 */
@Slf4j
@EnableTransactionManagement
@SpringBootApplication
@EnableJpaRepositories
public class RedisDemoApplication implements ApplicationRunner {
    @Autowired
    private CoffeeService coffeeService;

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

    /**
     * 设置RedisTemplate Bean
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String,Coffee> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Coffee> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

    @Bean
    public LettuceClientConfigurationBuilderCustomizer customizer(){
        return builder -> builder.readFrom(ReadFrom.MASTER_PREFERRED);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        Optional<Coffee> c = coffeeService.findOneCoffee("mocha");
        log.info("Coffee {}",c);

        for(int i=0;i<5;i++){
            c = coffeeService.findOneCoffee("mocha");
        }

        log.info("Value from Redis: {}",c);
    }
}

原文地址:https://www.cnblogs.com/ukzq/p/13415057.html