memcached

springboot 引入memcached
0、安装memcache
启动memcache

1、pom.xml 引入依赖

 <dependency>
     <groupId>net.spy</groupId>
     <artifactId>spymemcached</artifactId>
     <version>2.12.2</version>
 </dependency>

MemcachedController:

package com.example.springbootlearn.controller;

import com.example.springbootlearn.runner.MemcachedRunner;
import net.spy.memcached.MemcachedClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class MemcachedController {

    @Resource
    private MemcachedRunner memcachedRunner;


    @RequestMapping("/hellomemcache")
    @ResponseBody
    public String memcache() {
        MemcachedClient memcachedClient = memcachedRunner.getMemcachedClient();
        memcachedClient.set("hello",1000,"memcached!");
        return  (String) memcachedClient.get("hello");
    }
}

MemcacheConfiguration:

package com.example.springbootlearn.config;


import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "memcache")
public class MemcacheConfiguration {

    private String ip;

    private int port;
}

MemcachedRunner:
实现CommandLineRunner接口,在项目启动的时候配置 MemcachedClient

package com.example.springbootlearn.runner;

import com.example.springbootlearn.config.MemcacheConfiguration;
import net.spy.memcached.MemcachedClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

@Component
public class MemcachedRunner implements CommandLineRunner {

    protected Logger logger =  LoggerFactory.getLogger(this.getClass());

    @Resource
    private MemcacheConfiguration memcacheConfiguration;

    private MemcachedClient memcachedClient = null;

    @Override
    public void run(String... args) throws Exception {
        try {
            memcachedClient = new MemcachedClient(new InetSocketAddress(memcacheConfiguration.getIp(), memcacheConfiguration.getPort()));
        } catch (Exception ex) {
            logger.error("初始化MemcachedClient失败 ",ex);
        }

    }

    public MemcachedClient getMemcachedClient() {
        return memcachedClient;
    }
}

application.properties:
memcache配置项

memcache.ip=127.0.0.1
memcache.port=11211

启动项目,访问接口
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值