spring boot整合memcached

来源:互联网 发布:php打印直角三角形 编辑:程序博客网 时间:2024/06/04 23:35

官方术语:

          Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载。它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态、数据库驱动网站的速度。Memcached基于一个存储键/值对的hashmap。其守护进程(daemon )是用C写的,但是客户端可以用任何语言来编写,并通过memcached协议与守护进程通信。

          当然还有很多的内存缓存系统,如:redis..这里就不做渗透了,此处主要讲解memcached与spring boot的整合,其实和spring的整合是差不多的,

此处有整理一遍,是为了补充之Spring与Memcached-xmemcached整合这篇文章,

基于memcached的工具包有很多,如:com.danga.java-memcached,还有   com.googlecode.xmemcache.xmemcached , 之前已经介绍了xmemcached,基于xml配置文件的,

这里将讲下java-memcached基于配置文件和注解的用法

1:基于xml配置文件的用法

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">    <bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"          factory-method="getInstance" init-method="initialize"          destroy-method="shutDown">        <constructor-arg>            <value>neeaMemcachedPool</value>        </constructor-arg>        <property name="servers">            <list>                <value>${memcache.server}</value>            </list>        </property>        <property name="initConn">            <value>${memcache.initConn}</value>        </property>        <property name="minConn">            <value>${memcache.minConn}</value>        </property>        <property name="maxConn">            <value>${memcache.maxConn}</value>        </property>        <property name="maintSleep">            <value>${memcache.maintSleep}</value>        </property>        <property name="nagle">            <value>${memcache.nagle}</value>        </property>        <property name="socketTO">            <value>${memcache.socketTO}</value>        </property>    </bean>    <bean id="memcachedClient" class="com.danga.MemCached.MemCachedClient">        <constructor-arg>            <value>neeaMemcachedPool</value>        </constructor-arg>    </bean></beans>

memcached.properties配置文件

memcache.server=127.0.0.1:11211memcache.initConn=20memcache.minConn=10memcache.maxConn=50memcache.maintSleep=3000memcache.nagle=falsememcache.socketTO=3000

2:基于javabean注解

      application.properties增加memcached配置文件

   

#memcached缓存机制配置memcached.servers=127.0.0.1:11211memcached.weights=5memcached.initConn=20memcached.minConn=10memcached.maxConn=50memcached.maintSleep=3000memcached.nagle=falsememcached.socketTO=3000

      a>初始化Memcached IO池

package com.xyy.util.cached.memcached;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/** * memcached池 * @ClassName: SockIOPoolConfig  * @author wangqinghua * @date 2017年7月24日 下午2:22:59 */@Component@ConfigurationProperties(prefix = "memcached")public class SockIOPoolConfig {/** 服务地址 */private String[] servers;/** 权重 */    private Integer[] weights;    /** 初始化连接数 */    private int initConn;    /** 最小连接数 */    private int minConn;    /** 最大连接数 */    private int maxConn;    /** 睡眠时长 */    private long maintSleep;    private boolean nagle;    private int socketTO;public String[] getServers() {return servers;}public void setServers(String[] servers) {this.servers = servers;}public Integer[] getWeights() {return weights;}public void setWeights(Integer[] weights) {this.weights = weights;}public int getInitConn() {return initConn;}public void setInitConn(int initConn) {this.initConn = initConn;}public int getMinConn() {return minConn;}public void setMinConn(int minConn) {this.minConn = minConn;}public int getMaxConn() {return maxConn;}public void setMaxConn(int maxConn) {this.maxConn = maxConn;}public long getMaintSleep() {return maintSleep;}public void setMaintSleep(long maintSleep) {this.maintSleep = maintSleep;}public boolean isNagle() {return nagle;}public void setNagle(boolean nagle) {this.nagle = nagle;}public int getSocketTO() {return socketTO;}public void setSocketTO(int socketTO) {this.socketTO = socketTO;}}

    b>MemCachedClient初始化

package com.xyy.util.cached.memcached;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;import org.springframework.context.annotation.Bean;import org.springframework.stereotype.Component;import com.danga.MemCached.MemCachedClient;import com.danga.MemCached.SockIOPool;/** * MemCachedClient初始化 * @Conditional注释,此注释使得只有在特定条件满足时才启用一些配置。 * @ConditionalOnBean(仅仅在当前上下文中存在某个对象时,才会实例化一个Bean) * @ClassName: MemcachedConfig  * @author wangqinghua * @date 2017年7月24日 下午2:31:45 */@Componentpublic class MemcachedConfig {@Autowired    SockIOPoolConfig sockIOPoolConfig;    @Bean    public SockIOPool sockIOPool(){        //获取连接池的实例        SockIOPool pool = SockIOPool.getInstance();        //服务器列表及其权重        String[] servers = sockIOPoolConfig.getServers();        Integer[] weights = sockIOPoolConfig.getWeights();        //设置服务器信息        pool.setServers(servers);        pool.setWeights(weights);        //设置初始连接数、最小连接数、最大连接数、最大处理时间        pool.setInitConn(sockIOPoolConfig.getInitConn());        pool.setMinConn(sockIOPoolConfig.getMinConn());        pool.setMaxConn(sockIOPoolConfig.getMaxConn());        //设置连接池守护线程的睡眠时间        pool.setMaintSleep(sockIOPoolConfig.getMaintSleep());        //设置TCP参数,连接超时        pool.setNagle(sockIOPoolConfig.isNagle());        pool.setSocketConnectTO(sockIOPoolConfig.getSocketTO());        //初始化并启动连接池        pool.initialize();        return pool;    }    @Bean    @ConditionalOnBean(SockIOPool.class)    public MemCachedClient memCachedClient(){        return new MemCachedClient();    }}

使用方法和之前一样,

package com.xyy.controller;import java.util.HashMap;import java.util.Map;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.ModelAndView;import com.danga.MemCached.MemCachedClient;import com.xyy.model.Favorite;import com.xyy.service.FavoriteService;/** * Favorite控制层 * @ClassName: FavoriteController  * @author wangqinghua * @date 2017-07-13 15:09:50 */@RestController@RequestMapping("/favorite")public class FavoriteController{private static final Logger LOGGER = LoggerFactory.getLogger(FavoriteController.class);@Autowiredprivate FavoriteService favoriteService;@Autowiredprivate MemCachedClient  memCachedClient ;/**     * Favorite编辑     * @Title: update     * @param favorite 修改对象     * @return Object     * @author wujing      * @date 2017-07-13 15:09:50     *///@RequestMapping("/detail2/{id}")public Object detail2(@PathVariable Long id,ModelMap modelMap) {Map<String,Object> resultMap = new HashMap<String,Object>();try {Favorite tempFavorite = favoriteService.selectByPrimaryKey(id);resultMap.put("status", "success");resultMap.put("data", tempFavorite);} catch (Exception e) {resultMap.put("status", "error");resultMap.put("errorMsg", "系统异常");LOGGER.error("Favorite添加异常", e);}return resultMap;}@RequestMapping("/detail/{id}")public Object detail(@PathVariable Long id,ModelMap modelMap) {try {Favorite tempFavorite = (Favorite) memCachedClient.get("favorite:"+id);if(tempFavorite == null) {tempFavorite = favoriteService.selectByPrimaryKey(id);memCachedClient.set("favorite:"+id, tempFavorite);}modelMap.put("tempFavorite", tempFavorite);} catch (Exception e) {LOGGER.error("Favorite查询异常", e);}return new ModelAndView("favorite/detail");}}

memCachedClient的详细描述,请自行百度!再见

原创粉丝点击