spring、Mybatis、memcached是什么,干什么的我这里就不介绍了。
我这边用的是spring是3.2.4的,Mybatis是3.2.2的,数据库用的是postgreSQL
一、首先我们先来准备环境吧:
1、memcached的准备
1、下载及安装服务器端软件:
windows版本:http://yunpan.cn/QIU88cTyMbY6w
下载后将其解压,随便放在一个目录下,比如我放的是F:\mysoft\memcached\soft\server下,
在cmd中输入:
C:\Documents and Settings\admin>f:
F:\>cd F:\mysoft\memcached\soft\server\memcached-1.2.6-win3
F:\mysoft\memcached\soft\server\memcached-1.2.6-win32-bin>memcached.exe -dinstall(安装)
F:\mysoft\memcached\soft\server\memcached-1.2.6-win32-bin>memcached.exe -d start(启动)
默认的缓存大小为64M,如果不够用,请打开注册表,找到:
HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/memcached Server .
将其修改为:
“F:\mysoft\memcached\soft\server\memcached-1.2.6-win32-bin/memcached.exe” -d runservice -m 512
2、下载客户端包
http://yunpan.cn/QIUWjULt4ujd8
至此memcached准备好了。
2、jar包
如下:
3、我的项目结构图
二、接下来就是编写代码了(具体不讲了,语文没学好,不会面熟,直接上代码吧)
1、数据库表
CREATE TABLE users
(
id integer NOT NULL,
username character(20),
password character(20),
CONSTRAINT user_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE users
OWNER TOpostgres;
再插入点数据吧:
INSERT INTO users(id, username, password) VALUES (3, 'guozi3', '123456');
2、User.java
package org.mybatisSpring.example.entity;
import java.io.Serializable;
/*
* 注意,一定要实现Serializable,这个memcached要求的
*/
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = -6805933163488630157L;
private int id;
private String userName;
private String passWord;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
}
3、UserDao.java(注意这里一定要是接口,具体的实现不需要写,值需要在 UserMapper.xml配置即可,也可以向如下注释的用注解,这里不讲注解方式)
package org.mybatisSpring.example.dao;
import org.mybatisSpring.example.entity.User;
public interface UserDao {
// @Select("select * from users where id=#{id}")
public User getUserById(Integer id);
// @Delete("DELETE FROM users WHERE id=#{id}")
public int deleteById(int id);
// @Select("select count(*) from users")
public int countUser();
// @Insert("INSERT INTO users(id, username, password) VALUES (#{id}, #{userName}, #{passWord})")
public int saveUser(User user);
// @Update("UPDATE users SET username=#{userName}, password=#{passWord} WHERE id=#{id}")
public int updateUser(User user);
}
4、 UserMapper.xml( mybatis的映射文件当然你也可以用注解,那就不需要这个了 )
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 命名空间 是必须的 -->
<mapper namespace="org.mybatisSpring.example.dao.UserDao">
<select id="getUserById" parameterType="int" resultType="User">
select * from users where id=#{id}
</select>
</mapper>
5、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>MybatisSpringDemo</display-name>
<!-- 这个是后面加上的,没加之前启动服务器会报java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext这个错 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath*:/applicationContext.xml
</param-value>
</context-param>
<!-- 添加spring支持 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
6、config.properties(数据的配置信息及memcached的配置都放在这里)
dataSource.driver=org.postgresql.Driver
dataSource.url = jdbc:postgresql://127.0.0.1:5432/test
dataSource.username = postgres
dataSource.password = postgres
#memcached setting
memcache.server=127.0.0.1:11211
memcache.initConn=20
memcache.minConn=10
memcache.maxConn=50
memcache.maintSleep=3000
memcache.nagle=false
memcache.socketTO=3000
7、mybatis-config.xml(mybatis的配置文件)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- XML 配置文件包含对 MyBatis 系统的核心设置,包含获取数据库连接实例的数据源和 决定事务范围和控制的事务管理器。 -->
<configuration>
<typeAliases>
<typeAlias alias="User" type="org.mybatisSpring.example.entity.User" />
</typeAliases>
<mappers>
<mapper resource="org/mybatisSpring/example/entity/UserMapper.xml" />
</mappers>
</configuration>
8、UserService.java
package org.mybatisSpring.example.service;
import org.mybatisSpring.example.entity.User;
public interface UserService {
public User getUserById(Integer id);
}
9、UserServiceImpl.java(这里用到了memcached,但是用之前还要在spring的配置文件中配置,稍后会附上 spring的配置文件代码)
package org.mybatisSpring.example.service.Impl;
import org.mybatisSpring.example.dao.UserDao;
import org.mybatisSpring.example.entity.User;
import org.mybatisSpring.example.service.UserService;
import com.danga.MemCached.MemCachedClient;
public class UserServiceImpl implements UserService {
private UserDao userDao;
private MemCachedClient memCachedClient;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public void setMemCachedClient(MemCachedClient memCachedClient) {
this.memCachedClient = memCachedClient;
}
public MemCachedClient getMemCachedClient() {
return memCachedClient;
}
@Override
public User getUserById(Integer id) {
User user;
if(this.memCachedClient.get("user") != null){
System.out.println("缓存中的user");
System.out.println(this.memCachedClient.get("user"));
user = (User) this.memCachedClient.get("user");
}else{
System.out.println("数据库中查询出来的user");
user = userDao.getUserById(id);
this.memCachedClient.add("user", user);
}
return user;
}
}
10、applicationContext.xml(这个很重要,并且这里的default-lazy-init="true"会报 ERROR com.schooner.MemCached.SchoonerSockIOPool - attempting to get SockIO from uninitialized pool错误 )
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.2.xsd"
default-lazy-init="false">
<context:property-placeholder location="classpath:/config.properties" />
<!-- 数据源的定义 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${dataSource.driver}" />
<property name="url" value="${dataSource.url}" />
<property name="username" value="${dataSource.username}" />
<property name="password" value="${dataSource.password}" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="userDao" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="org.mybatisSpring.example.dao.UserDao" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
<bean id="userService" class="org.mybatisSpring.example.service.Impl.UserServiceImpl">
<property name="userDao" ref="userDao" />
<property name="memCachedClient" ref="memCachedClient" />
</bean>
<!-- memcached配置 -->
<bean id="memcachedPool" class="com.danga.MemCached.SockIOPool"
factory-method="getInstance" init-method="initialize"
destroy-method="shutDown">
<constructor-arg>
<value>memCachedPool</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>memCachedPool</value>
</constructor-arg>
</bean>
</beans>
11、下面我们来测试下Test.java
package org.mybatisSpring.example.test;
import org.mybatisSpring.example.entity.User;
import org.mybatisSpring.example.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
UserService userService = (UserService) context.getBean("userService");
User user = userService.getUserById(3);
System.out.println(user.getUserName());
}
}
结果:
第一次运行:
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
数据库中查询出来的user
guozi3
第二次运行(不是直接插数据库,而是从缓存中取的数据):
log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
缓存中的user
org.mybatisSpring.example.entity.User@12e8b9c
guozi3
好了,到这里就完成了。下班回家了