草庐IT

springboot整合redis-SpringBoot(22)

liwenruo 2023-04-17 原文

1. 在 Spring Boot 中集成 Redis

  (1)完成配置基础项。

    添加 Redis、MySQL、MyBatis 依赖。

  (2)配置MySQL、Redis服务器

    可以直接在application.yml文件中逬行配置,具体配置方法见以下代码:

查看代码

# 应用名称
spring:
  redis:
    host: 127.0.0.1
    port: 6379
    jedis:
      pool:
        max-active: 8
        max-wait: -1
        max-idle: 8
        min-idle: 0
    timeout: 5000
  datasource:
    druid:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true
      username: root
      password: 123456
    thymeleaf:
      mode: HTML
      encoding: UTF-8
      servlet:
        content-type: text/html
      cache: false
      prefix: classpath:/static/

mybatis:
  # spring boot集成mybatis的方式打印sql
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 应用服务 WEB 访问端口
server:
  port: 8080

  (3)在入口类加上@EnableCaching注解,开启缓存支持。

2. 配置Redis类

  要想启用Spring缓存支持,需创建一个CacheManager的Bean

package com.intehel.demo.config;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.lang.reflect.Method;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    //在缓存对象集合中,缓存是以key-value形式保存的
    //如果没有指定缓存的key,则Spring Boot 会使用SimpleKeyGenerator生成key
    @Override
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            //定义缓存key的生成策略
            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();
            }
        };
    }
    @SuppressWarnings("rawtypes")
    @Bean
    //缓存管理器 2.X版本
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheManager cacheManager = RedisCacheManager.create(connectionFactory);
        return cacheManager;
    }
    //缓存管理器 1.X版本
/*    public CacheManager cacheManager(@SuppressWarnings("rawtypes")RedisTemplate redisTemplate){
        return new RedisCacheManager(redisTemplate);
    }*/

    @Bean
    //注册成Bean被Spring管理,如果没有这个Bean,则Redis可视化工具中的中文内容都会以二进制存储,不易检查
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<String,Object>();
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory){
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        return stringRedisTemplate;
    }
}

3.创建测试实体类

  创建用于数据操作的测试实体类,见以下代码:

package com.intehel.demo.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person implements Serializable {
    private Long id;
    private String name;
    private Integer age;
    private String address;
}

4. 实现实体和数据表的映射关系

package com.intehel.demo.mapper;

import com.intehel.demo.domain.Person;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

@Repository
@Mapper
public interface PersonMapper {
    @Insert("insert into person(name, age,address) values(#{name},#{age},#{address})")
    int addPerson(@Param("name")String name, @Param("age")String age, @Param("address")String address);
    @Select("select * from person where id = #{id}")
    Person findById(@Param("id")String id);
    @Update("update person set age = #{age},name = #{name},address = #{address} where id = #{id}")
    int updateById(Person person);
    @Delete("delete from person where id = #{id}")
    void deleteById(@Param("id")String id);
}

5. 创建Redis缓存服务层

package com.intehel.demo.service;

import com.intehel.demo.domain.Person;
import com.intehel.demo.mapper.PersonMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "person")
public class PersonService {
    @Autowired
    PersonMapper personMapper;
    @Cacheable(key = "#p0")
    public Person selectPerson(String id){
        System.out.println("selectPerson");
        return personMapper.findById(id);
    }
    @CachePut(key = "#p0")
    public void updatePerson(Person person){
        System.out.println("updatePerson");
        personMapper.updateById(person);
    }
    @CacheEvict(key = "#p0",allEntries = true)
    public void deletePerson(String id){
        System.out.println("deletePerson");
        personMapper.deleteById(id);}
}

代码解释如下。

  • @Cacheable:将查询结果缓存到Redis中。
  • key="#p0":指定传入的第1个参数作为Redis的key。
  • @CachePut:指定key, 将更新的结果同步到Redis中。
  • @CacheEvict:指定key, 删除缓存数据。
  • @allEntries=true:方法调用后将立即清除缓存

6.完成增加、删除、修改和查询测试API

package com.intehel.demo.controller;

import com.intehel.demo.service.PersonService;
import com.intehel.demo.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class PersonController {
    @Autowired
    PersonService personService;
    @RequestMapping(value = "/{id}")
    public Person selectPerson(@PathVariable String id){
        return personService.selectPerson(id);
    }
    @RequestMapping(value = "/update")
    public String updatePerson(@RequestBody Person person){
        personService.updatePerson(person);
        return "success";
    }
    @RequestMapping(value = "/delete/{id}")
    public String deletePerson(@PathVariable String id){
        personService.deletePerson(id);
        return "delete success";
    }
}

  启动项目,多次访问http://localhost:8080/user/1 第一次时控制台会出现select信息,代表对数据库进行了查询操作。后面再访问时则不会出现提示,表示没有对数据库执行操作,而是使用 Redis中的缓存数据。

有关springboot整合redis-SpringBoot(22)的更多相关文章

  1. springboot定时任务 - 2

    如果您希望在Spring中启用定时任务功能,则需要在主类上添加 @EnableScheduling 注解。这样Spring才会扫描 @Scheduled 注解并执行定时任务。在大多数情况下,只需要在主类上添加 @EnableScheduling 注解即可,不需要在Service层或其他类中再次添加。以下是一个示例,演示如何在SpringBoot中启用定时任务功能:@SpringBootApplication@EnableSchedulingpublicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.ru

  2. 基于SpringBoot的线上日志阅读器 - 2

    软件特点部署后能通过浏览器查看线上日志。支持Linux、Windows服务器。采用随机读取的方式,支持大文件的读取。支持实时打印新增的日志(类终端)。支持日志搜索。使用手册基本页面配置路径配置日志所在的目录,配置后按回车键生效,下拉框选择日志名称。选择日志后点击生效,即可加载日志。windows路径E:\java\project\log-view\logslinux路径/usr/local/XX历史模式历史模式下,不会读取新增的日志。针对历史文件可以分页读取,配置分页大小、跳转。历史模式下,支持根据关键词搜索。目前搜索引擎使用的是jdk自带类库,搜索速度相对较低,优点是比较简单。2G日志全文搜

  3. springboot使用validator进行参数校验 - 2

    1.依赖导入org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-validation2.validation常用注解@Null被注释的元素必须为null@NotNull被注释的元素不能为null,可以为空字符串@AssertTrue被注释的元素必须为true@AssertFalse被注释的元素必须为false@Min(value)被注释的元素必须是一个数字,其值必须大于等于指定的最小值@Max(value)被注释的元素必须是一个数字,其值必须小于等于指定的最大值@D

  4. ruby - 如何将 Interactive Ruby 整合到我的开发过程中? - 2

    我正在尝试找到一种更好的方法将IRB与我的常规ruby​​开发集成。目前我很少在我的代码中使用IRB。我只用它来验证语法或尝试一些小的东西。我知道我可以将我自己的代码加载到ruby​​中作为一个require'mycode'但这通常不符合我的编程风格。有时我要检查的变量超出范围或在循环内。有没有一种简单的方法可以启动我的脚本并在IRB内的某个点卡住?我想我正在寻找一种更简单的方法来调试我的ruby​​代码而不破坏我的F5(编译)键。也许有经验的ruby开发者可以和我分享一个更精简的开发方法。 最佳答案 安装ruby​​-debugg

  5. ruby - 使用 Drupal 和 Ruby。有没有人整合两者? - 2

    我开始了一个小型网络项目并使用Drupal来构建它。到目前为止,还不错:您可以快速建立一个不错的面向CMS的网站,通过模块添加社交功能,并且您有一个广泛的API可以在一个架构良好的平台中进行自定义。现在问题来了:网站的增长超出了最初的计划,我发现自己正处于认真开始为它编写代码的境地。由于Drupal项目,我对PHP有了新的认识,但我想用Ruby来做。我会感觉更舒服,以后维护起来更容易,我可以在其他Ruby/Rails应用程序中重用它。随着时间的推移,我想我会用Ruby重写Drupal中的现有部分。基于此,问题是:是否有人将两者(成功或失败的故事)结合起来?这是一个相当大的决定,但我在G

  6. 停车系统源码-基于springboot+uniapp开源项目 - 2

    Iparking停车收费管理系统-可商用介绍Iparking是一款基于springBoot的停车收费管理系统,支持封闭车场和路边车场,支持微信支付宝多种支付渠道,支持多种硬件,涵盖了停车场管理系统的所有基础功能。技术栈Springboot,MybatisPlus,Beetl,Mysql,Redis,RabbitMQ,UniApp功能云端功能序号模块功能描述1系统管理菜单管理配置系统菜单2系统管理组织管理管理组织机构3系统管理角色管理配置系统角色,包含数据权限和功能权限配置4系统管理用户管理管理后台用户5系统管理租户管理多租户管理6系统管理公众号配置租户公众号配置7系统管理操作日志审计日志8系统

  7. 优化大数据量查询方案——SpringBoot(Cloud)整合ES - 2

    一、Elasticsearch简介实际业务场景中,多端的查询功能都有很大的优化空间。常见的处理方式有:建索引、建物化视图简化查询逻辑、DB层之上建立缓存、分页…然而随着业务数据量的不断增多,总有那么一张表或一个业务,是无法通过常规的处理方式来缩短查询时间的。在查询功能优化上,作为开发人员应该站在公司的角度,本着优化客户体验的目的去寻找解决方案。本人有幸做过Tomcat整合solr,今天一起研究一下当前比较火热的Elasticsearch搜索引擎。Elasticsearch是一个非常强大的搜索引擎。它目前被广泛地使用于各个IT公司。Elasticsearch是由Elastic公司创建。它的代码位

  8. SpringBoot+Netty实现TCP客户端实现接收数据按照16进制解析并存储到Mysql以及Netty断线重连检测与自动重连 - 2

    场景在SpringBoot项目中需要对接三方系统,对接协议是TCP,需实现一个TCP客户端接收服务端发送的数据并按照16进制进行解析数据,然后对数据进行过滤,将指定类型的数据通过mybatis存储进mysql数据库中。并且当tcp服务端断连时,tcp客户端能定时检测并发起重连。全流程效果 注:博客:霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主实现1、SpringBoot+Netty实现TCP客户端本篇参考如下博客,在如下博客基础上进行修改Springboot+Netty搭建基于TCP协议的客户端(二):https://www.cnblogs.com/haolb

  9. Java面试--SpringBoot启动流程 - 2

    一、SpringBoot是什么SpringBoot是依赖于Spring的,比起Spring,除了拥有Spring的全部功能以外,SpringBoot无需繁琐的Xml配置,这取决于它自身强大的自动装配功能;并且自身已嵌入Tomcat、Jetty等web容器,集成了SpringMvc,使得SpringBoot可以直接运行,不需要额外的容器,提供了一些大型项目中常见的非功能性特性,如嵌入式服务器、安全、指标,健康检测、外部配置等,其实Spring大家都知道,Boot是启动的意思。所以,SpringBoot其实就是一个启动Spring项目的一个工具而已,总而言之,SpringBoot是一个服务于框架的

  10. javascript - QuotaExceededError (DOM Exception 22) : The quota has been exceeded on Safari in incognito - 2

    当我处于隐身模式时,我在Safari上收到QuotaExceededError(DOMException22):Thequotahasbeenexceeded.。我经历过类似的问题:QuotaExceededError:Domexception22:Anattemptwasmadetoaddsomethingtostoragethatexceededthequota但是他们谈论setItem,我在其他地方得到了这个错误。我在这一行收到此错误:localStorage['gallery.extensions']=JSON.stringify({});或localStorage['asdf

随机推荐