Memcached 的安装与使用;SpringBoot 整合 Memcached 代码详解

Memcached 的安装与使用;SpringBoot 整合 Memcached 代码详解
- Memcached 的下载安装:
  • 下载地址为:http://static.runoob.com/download/memcached-win64-1.4.4-14.zip
  • 安装:以管理员身份打开 CMD:执行下列命令安装 Memcached。
    在这里插入图片描述
  • Memcached 的启停:
    在这里插入图片描述
- Memcached 的三种客户端介绍:
  • Memcached Client For Java:最早期客户端,稳定可靠,用户多。
  • SpyMemcached:效率更高。
  • Xmemcached:并发处理更好。
- SpringBoot 未提供对 Memcached 的整合,需要使用硬编码方式实现客户端初始化管理。
  • 目录结构如下:
    在这里插入图片描述
- 通过配置类注册 Bean:
// XMemcachedConfig.java
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;

@Configuration
public class XMemcachedConfig {
    
    @Bean
    public MemcachedClient memcachedClient(){
        MemcachedClient memcachedClient = null;
        try {
            MemcachedClientBuilder builder = new XMemcachedClientBuilder("localhost:11211");
            memcachedClient = builder.build();
        }catch (Exception e){
            e.printStackTrace();
        }
        return memcachedClient;
    }
    
}
- 实体类 Book.java
package com.example.springboot.entity;

import lombok.*;

import java.io.Serializable;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book implements Serializable {

    private String id;
    private String name;
    private String description;
    private Float price;

}

- 在业务层使用 MemcachedClient 如下:
// BookService.java
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.springboot.entity.Book;

public interface BookService extends IService<Book> {
    Book setCacheById(String id);
    Boolean checkCacheById(String id, String name);
}

// BookServiceImpl.java
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.dao.BookDao;
import com.example.springboot.entity.Book;
import com.example.springboot.service.BookService;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.XMemcachedClient;
import net.rubyeye.xmemcached.exception.MemcachedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeoutException;

@Service
public class BookServiceImpl extends ServiceImpl<BookDao, Book> implements BookService {

    @Autowired
    private MemcachedClient memcachedClient;

    @Override
    public Book setCacheById(String id) {
        try {
        	// 往 memcached 中放数据,第一个参数为key
        	// 第二个参数为过期时间(0表示永不过期)
        	// 第三个参数为要存放到缓存中的数据(需实现序列化)
            memcachedClient.set(id, 0, getById(id));
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (MemcachedException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean checkCacheById(String id, String name) {
        Book cacheData = null;
        try {
        	// 根据key, 从缓存中取数据
            cacheData = memcachedClient.get(id);
        } catch (TimeoutException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (MemcachedException e) {
            e.printStackTrace();
        }
        return name.equals(cacheData.getName());
    }
}
- 表现层 BookController.java 代码:
import com.example.springboot.entity.Book;
import com.example.springboot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    @GetMapping("{id}")
    public Book getById(@PathVariable String id){
        return bookService.setCacheById(id);
    }

    @PostMapping
    public Boolean checkById(@RequestBody Book book){
        return bookService.checkCacheById(book.getId(), book.getName());
    }
}
- 通过 Postman 测试如下:
  • 往 Memcached 中放数据:
    在这里插入图片描述

  • 从 Memcached 中取数据:
    在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!要将MemcachedSpring Boot集成,您可以遵循以下步骤: 1. 添加依赖:在您的Spring Boot项目的pom.xml文件中,添加以下依赖项来引入Memcached客户端库: ```xml <dependency> <groupId>com.google.code.simple-spring-memcached</groupId> <artifactId>spring-cache</artifactId> <version>3.6.1</version> </dependency> ``` 2. 配置Memcached连接:在application.properties或application.yml文件中,添加Memcached服务器的连接配置,例如: ```properties spring.cache.type=simple spring.cache.simple.cache-names=myCache spring.cache.simple.servers=localhost:11211 ``` 3. 创建缓存配置类:创建一个用于配置缓存的类,例如: ```java @Configuration @EnableCaching public class CacheConfig extends CachingConfigurerSupport { @Bean @Override public CacheManager cacheManager() { SimpleCacheManager cacheManager = new SimpleCacheManager(); cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("myCache"))); return cacheManager; } } ``` 4. 在需要缓存的方法上添加缓存注解:在您的服务类中,选择要进行缓存的方法,并使用`@Cacheable`注解来标记它们。例如: ```java @Service public class MyService { @Cacheable("myCache") public String getDataFromCache(String key) { // 从数据库或其他地方获取数据的逻辑 return result; } } ``` 现在,当调用`getDataFromCache`方法时,它将首先检查缓存中是否存在具有给定键的数据。如果存在,它将返回缓存的数据,而不执行实际的方法体。如果缓存中不存在该数据,则方法体将被执行,并将结果放入缓存供以后使用。 这样,您就成功地将MemcachedSpring Boot集成了。希望对您有所帮助!如有任何问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值