首页 > 其他分享 >SpringBoot集成Memcached实现高效缓存

SpringBoot集成Memcached实现高效缓存

时间:2023-12-21 12:02:23浏览次数:30  
标签:缓存 SpringBoot nettydemo id user import Memcached example

一、前言

Memcached是一款高性能的分布式内存对象缓存系统,可以用来缓存SQL查询结果、API调试结果等。使用Memcached可以减少对数据库的查询次数,提高系统性能。它主要用于减轻数据库负载,提供应用系统,减少数据库压力。SpringBoot可以快速集成Memcached实现对缓存到读写操作。


二、安装和配置

下载和安装Memcached我们可以下载我们系统的相关版本。

我们下载好之后,解压文件夹得到下面文件。

SpringBoot集成Memcached实现高效缓存_SpringBoot

运行方法:

我们需要命令行到当前目录执行以下命令。

1.先安装服务 memcached.exe -d install 以管理员身份运行。

2.启动服务 memcached.exe -d start

3.关闭服务  memcached.exe -d stop

我们启动服务后也可以在服务上找到刚才我们创建的服务。

SpringBoot集成Memcached实现高效缓存_缓存_02

三、常用命令

set:存储数据  set key flags exptime bytes [noreply]  value  

get:获取数据 get key

delete:删除数据 delete key

incr:增加一个值 incr key increment_value

decr:减少一个值: decr key decrement_value

四、SpringBoot集成Memcached

1.添加依赖

<dependency>
            <groupId>com.googlecode.xmemcached</groupId>
            <artifactId>xmemcached</artifactId>
            <version>2.4.5</version>
        </dependency>

2.Memcached配置

package com.example.nettydemo.config;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

/**
 * @author qx
 * @date 2023/12/20
 * @des memcached的配置类
 */
@Configuration
public class MemcachedConfig {

    @Bean
    public MemcachedClient getMemcachedClient() throws IOException {
        //memcached默认对外服务端口11211。
        MemcachedClientBuilder memcachedClientBuilder = new XMemcachedClientBuilder("localhost:11211");
        return memcachedClientBuilder.build();
    }
}

3.创建数据实体

package com.example.nettydemo.entity;

import lombok.Data;

import javax.persistence.*;
import java.io.Serializable;

/**
 * @author qx
 * @date 2023/12/20
 * @des 测试实体
 */
@Entity
@Table(name = "t_user")
@Data
public class User implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    private Integer age;

}

4.创建服务类

具体步骤是先获取缓存的操作,如果缓存存在就直接返回,或者缓存不存在就请求数据库然后把数据添加到缓存中并返回。

package com.example.nettydemo.service;

import com.example.nettydemo.entity.User;
import com.example.nettydemo.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeoutException;

/**
 * @author qx
 * @date 2023/12/20
 * @des
 */
@Slf4j
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Resource
    private MemcachedClient memcachedClient;

    public User getUserById(Long id) throws InterruptedException, TimeoutException, MemcachedException {
        // 使用Memcached查询指定的缓存
        User user = memcachedClient.get(String.valueOf(id));
        if (user == null) {
            log.info("没有缓存,请求数据库");
            user = userRepository.findById(id).orElse(null);
            if (user != null) {
                // 设置缓存
                memcachedClient.set(String.valueOf(id), 300, user);
            }
        } else {
            log.info("使用缓存返回数据");
        }
        return user;
    }

}

5.控制层

package com.example.nettydemo.controller;

import com.example.nettydemo.entity.User;
import com.example.nettydemo.service.UserService;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeoutException;

/**
 * @author qx
 * @date 2023/12/20
 * @des
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User selectUserById(@PathVariable("id") Long id) throws InterruptedException, TimeoutException, MemcachedException {
        return userService.getUserById(id);
    }
}

6.测试

我们请求查询ID为1的数据。http://localhost:8080/user/1

我们的目的是第一次没有缓存会先请求数据库,第二次请求会直接使用缓存。

SpringBoot集成Memcached实现高效缓存_SpringBoot_03

我们查看控制台的日志显示数据库的查询语句。

2023-12-20 17:59:07.469  INFO 19504 --- [nio-8080-exec-5] c.example.nettydemo.service.UserService  : 没有缓存,请求数据库
Hibernate: select user0_.id as id1_1_0_, user0_.age as age2_1_0_, user0_.name as name3_1_0_ from t_user user0_ where user0_.id=?

我们第二次请求数据同样返回了数据,这是因为返回了缓存中的数据。

SpringBoot集成Memcached实现高效缓存_memcached_04

控制台的日志显示使用了缓存返回数据。

2023-12-20 18:00:34.621  INFO 19504 --- [nio-8080-exec-7] c.example.nettydemo.service.UserService  : 使用缓存返回数据

这样我们就完成了SpringBoot集成Memached实现简单的数据缓存。

标签:缓存,SpringBoot,nettydemo,id,user,import,Memcached,example
From: https://blog.51cto.com/u_13312531/8920962

相关文章

  • SpringBoot整合Dubbo常用注解类说明
    SpringBoot与Dubbo的整合pom依赖:<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.spr......
  • Spring Boot —— Caffeine(内存缓存器)
    项目中需要用一个替代concurrenthashmap能够帮忙过期或者防止一直putoom所以使用 优点内存管理优化Caffeine使用了一种基于堆外内存的存储模型,通过直接内存访问,避免了Java堆内存的垃圾回收开销。这种内存管理优化可以减少垃圾回收对应用性能的影响,提供更高的缓存读写性能......
  • 缓存:系统设计中至关重要的一环
    什么是缓存?缓存就像是一个超快速的存储区域,保存了计算机或手机经常使用的内容的副本,这样可以在不访问较慢的主存储器的情况下快速获取。一个现实中的例子可以是,每当我们购买杂货时,通常会倾向于大量购买,这样可以让杂货多存放一段时间,避免频繁去市场购买,这其实就是将杂货缓存在我......
  • 分布式缓存
    单点redis的问题数据丢失问题:Redis是内存存储,服务重启可能会丢失数据。解决:数据持久化并发能力问题:单节点并发能力不足。解决:主从集群,读写分离。故障恢复:需要自动的故障恢复手段。解决:Redis哨兵,实现健康检测和自动恢复。存储能力问题:单节点Redis难以满足海量数据存储。解决:搭......
  • 【SpringBootWeb入门-16】Mybatis-基础操作-多条件查询操作&XML文件配置SQL
    1、章节回顾上一篇文章我们讲解了Mybatis的增改查操作,本篇继续学习Mybatis的复杂查询操作(多条件查询)。2、增删改查操作-多条件查询操作根据条件姓名、性别、入职时间来查询员工表emp数据,其中员工姓名支持模糊匹配,性别进行精确匹配,入职时间进行范围查询,查询结果按照最后修改时间......
  • Redis缓存
    Redis(RemoteDictionaryServer)是一个开源的高性能键值对(key-value)存储系统,常被用作数据库、缓存和消息代理。它支持多种数据结构,如字符串、哈希表、列表、集合和有序集合。 为什么要用Redis?使用Redis有多个原因,包括:高性能:Redis是基于内存存储计算的,其性能速度远超MySQL等数......
  • springboot051医院管理系统-计算机毕业设计源码+LW文档
    一、立题依据(研究的目的与意义及国内外现状):现如今,互联网的广泛普及与应用,标志着信息化的时代已经到来,管理信息化行业在生活中占据着越来越重要的地位,信息化的服务与管理,大大简化了传统的管理模式,很大程度上,改善了使得人们的生活水平和工作方式。简单的来说医院管理信息化的形式非......
  • springboot053宠物咖啡馆平台-计算机毕业设计源码+LW文档
    摘要随着信息技术在管理上越来越深入而广泛的应用,管理信息系统的实施在技术上已逐步成熟。本文介绍了基于SpringBoot的宠物咖啡馆平台的设计与实现的开发全过程。通过分析基于SpringBoot的宠物咖啡馆平台的设计与实现管理的不足,创建了一个计算机管理基于SpringBoot的宠物咖啡馆......
  • springboot054飘香水果购物网站 -计算机毕业设计源码+LW文档
    摘要随着信息互联网购物的飞速发展,一般企业都去创建属于自己的电商平台以及购物管理系统。本文介绍了飘香水果购物网站的开发全过程。通过分析企业对于飘香水果购物网站的需求,创建了一个计算机管理飘香水果购物网站的方案。文章介绍了飘香水果购物网站的系统分析部分,包括可行性分......
  • springboot055服装生产管理-计算机毕业设计源码+LW文档
    一、现状、意义和目的1.背景与现状近年来,随着经济全球化与科技管理信息化的协同发展,而又因服装业所面对的是终端消费者市场,是由消费者主导的供应链,服装需求更加多样化,致使服装市场的竞争日趋激烈。随之产品生命周期变短,消费者数量的不断增多及需求快速多变等特性导致服装需求激增,协......