首页 > 解决方案 > 如何将 memcached 与 spring MVC API 连接以获取和设置数据

问题描述

我是 memcached 和 Spring MVC 的新手,我正在尝试创建一个 rest api,它将在 memcached 中设置一些值。我也可以检索。但我没有找到连接到 memcached 的正确方法。

消费者配置:

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;   import com.btmatthews.springboot.memcached.EnableMemcached;

@EnableMemcached
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "msg91.consumers.consumer")
public class consumerConfiguration {

}

ConsumerInitializer 类:

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class consumerInitializer  extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] { consumerConfiguration.class };
    }

    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

}

控制器类:

@RestController
public class consumerController {
    @Autowired
    private MemcachedClient memcachedClient;

    @RequestMapping(value="/queues/{queueName}/thread-counts/{threadCount}", method = RequestMethod.POST)
    public void setThreadCount(@PathVariable String queueName, @PathVariable int threadCount) {
        System.out.println("Queue name is "+queueName);
        System.out.println("Thread count is "+threadCount);     
        memcachedClient.set(queueName, 0, threadCount);//Setting the values in memcache which I get in api
    }

    @RequestMapping(value="/queues/{queueName}/thread-counts", method = RequestMethod.GET)
    public void getThreadCount(@PathVariable String queueName) {
        System.out.println("Queue value is"+queueName);
        int threadCount = (Integer)memcachedClient.get(queueName);
        System.out.println("Thread count for " + queueName + " is " + threadCount);
    }
}

Spring-调度程序-servlet.xml:

<bean name="defaultMemcachedClient" class="com.google.code.ssm.CacheFactory">
  <property name="cacheClientFactory">
        <bean class="com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl" />
  </property>
  <property name="addressProvider">
        <bean class="com.google.code.ssm.config.DefaultAddressProvider">
 <property name="address" value="127.0.0.1:11211" />
  </bean>
  </property>

它不工作,给出错误:

Web 应用程序 [/consumer-api] 中的 Servlet [spring-dispatcher] 抛出 load() 异常 java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

我认为我无法正确提供 memcache 的路径或无法连接到 memcached。请帮我解决这个问题。

标签: restspring-mvcspring-bootmemcachedspymemcached

解决方案


推荐阅读