memcached整合springboot

整合

依赖
    
            com.googlecode.xmemcached
            xmemcached
            2.4.5
        
配置

application.yml配置如下

memcached:
  //memcached服务器节点
  servers: 192.168.139.145:2222 192.168.139.145:6666
  //nio连接池的数量
  poolSize: 10
  //是否启用url  encode机制
  sanitizeKeys: false

构建一个config bean,对应配置文件内容

@Component
@ConfigurationProperties(prefix = "memcached")
public class XMemcachedProperties {

    private String servers;
    private Integer poolSize;
    private Boolean  santizeKeys;
    //省略getter-setter
}

构造MemcachedClient

  • 构造MemcachedClient Bean之前,需要先构造MemcachedClientBuilder
    @Autowired
    private XMemcachedProperties properties;

    //构建builder
    @Bean
    public MemcachedClientBuilder getXMBuilder(){
        MemcachedClientBuilder memcachedClientBuilder = null;
         try {
            String server =properties.getServers();
            memcachedClientBuilder= new XMemcachedClientBuilder(server);

            memcachedClientBuilder.setFailureMode(false);
            memcachedClientBuilder.setSanitizeKeys(properties.getSantizeKeys());
            memcachedClientBuilder.setConnectionPoolSize(properties.getPoolSize());
            memcachedClientBuilder.setCommandFactory(new BinaryCommandFactory());
            memcachedClientBuilder.setOpTimeout(3000);
            memcachedClientBuilder.setSessionLocator(new KetamaMemcachedSessionLocator());
            return  memcachedClientBuilder;
         }catch (Exception e){
            e.printStackTrace();
         }
         return null;
    }
  • 构造MemcachedClient

    @Bean
    public MemcachedClient getXMClient(MemcachedClientBuilder builder){
        MemcachedClient client = null;
        try {
            client = builder.build();
            return client;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

测试

  • 编写一个Service,注入MemcachedClient ,调用set/get命令

@Service
public class ShowService {

    @Autowired
    private MemcachedClient memcachedClient;


    public void showAdd(String key,String value){
        try {
            memcachedClient.set(key,3600,value);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    public String showQuery(String key){
        try {
            return  memcachedClient.get(key);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

}
  • 编写junit
@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

    @Autowired
    private ShowService showService;

    @Test
    public void contextLoads() {

        String key = "k1";
        String value= "k1value";

        String key2 = "k2";
        String value2= "k2value";
        showService.showAdd(key,value);
        showService.showAdd(key2,value2);
        System.out.println(showService.showQuery(key));
        System.out.println(showService.showQuery(key2));
    }

}

你可能感兴趣的:(memcached整合springboot)