这里结合SSM框架使用,Mac系统
首先需要安装Redis
- 安装包:Redis安装包
- 解压安装包,放在usr/local下,改名redis
- 进入终端:cd /usr/local/redis
- make
- sudo make install
- 输入电脑设置的密码111111
- 安装完成
- 配置:
- 打开redis.conf文件
- 在500行左右,把# require pass foobared 改为 requirepass 自己设置密码
- 保存退出
- 启动:
- cd src/
- ./redis-server ../redis.conf
- 终止:
- ctrl+c
- 使用:
- 新建一个终端窗口
- /usr/local/redis/src/redis-cli -a 自己前面设置的密码
- 简单命令使用
- 查看所有的key: keys *
- 赋值: set name zhangsan
- 取值: get name
- 如果不存在key设置值:setnx name1 lisi
- 拼接: append name zhaoliu
- 删除: del name
- 重命名: rename name1 新key值
- 同时设置多个值: meet name1 123 age 22
- 查看某key是否存在: exists key值
- 加一: incr age (age=23)
- 赋新值: getset name 123
SSM框架中的使用(先搭好框架!!!!!!!!!!)
- 首先添加Redis的依赖
<!--Redis的依赖-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
- Student类:必须实现序列化
public class Student implements Serializable{
package com.lanou.bean;
import java.io.Serializable;
/**
* Created by dllo
*/
public class Student implements Serializable{
private int id;
private String name;
private String hobby;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", hobby='" + hobby + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
}
- RedisCache类
package com.lanou.cache;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import redis.clients.jedis.exceptions.JedisConnectionException;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Created by dllo
*/
public class RedisCache implements Cache {
private final String id;
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private static JedisConnectionFactory jedisConnectionFactory;
//jedis框架提供的Redis连接工厂
//我们使用spring框架来赋值(注入)
public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.jedisConnectionFactory = jedisConnectionFactory;
}
//添加id的构造方法
public RedisCache(String id) {
if (id == null) {
throw new IllegalArgumentException("id不能为空");
}
this.id = id;
}
//获取缓存对象的唯一标识
@Override
public String getId() {
return this.id;
}
//将key-value保存到缓存中
//key可以是任何对象,但是一般第一使用CacheKey对象
//value是查询结果,List类型
@Override
public void putObject(Object key, Object value) {
JedisConnection connection = null;
try {
//获取一个Connection
connection = (JedisConnection) jedisConnectionFactory.getConnection();
//jedis提供了一个序列化类,帮助转换
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
connection.set(serializer.serialize(key), serializer.serialize(value));
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
}
//从缓存中获取key对应的Value值
@Override
public Object getObject(Object key) {
JedisConnection connection = null;
Object result = null;
try {
//获取一个Connection
connection = (JedisConnection) jedisConnectionFactory.getConnection();
//jedis提供了一个序列化类,帮助转换
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
byte[] value = connection.get(serializer.serialize(key));
result = serializer.deserialize(value);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
return result;
}
//移除key对应的缓存
//可选实现,没有被核心框架调用
@Override
public Object removeObject(Object key) {
JedisConnection connection = null;
Object result = null;
try {//获取一个Connection
connection = (JedisConnection) jedisConnectionFactory.getConnection();
//jedis提供了一个序列化类,帮助转换
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
byte[] value = connection.get(serializer.serialize(key));
result = serializer.deserialize(value);
connection.expire(serializer.serialize(key), 0);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
return result;
}
//清空缓存
@Override
public void clear() {
JedisConnection connection = null;
try {
//获取一个Connection
connection = (JedisConnection) jedisConnectionFactory.getConnection();
connection.flushDb();
connection.flushAll();
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
}
//获取缓存中存储的键/值对的 数量
@Override
public int getSize() {
JedisConnection connection = null;
int result = 0;
try {
//获取一个Connection
connection = (JedisConnection) jedisConnectionFactory.getConnection();
result = connection.dbSize().intValue();
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
return result;
}
//获取读写锁
//不是必须要实现的方法
@Override
public ReadWriteLock getReadWriteLock() {
return this.getReadWriteLock();
}
}
- RedisCacheTransfer类
package com.lanou.cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
/**
* Created by dllo
*/
public class RedisCacheTransfer {
@Autowired
public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
}
}
-MainController类
package com.lanou.controller;
import com.lanou.bean.Student;
import com.lanou.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by dllo
*/
@Controller
public class MainController {
@Resource
private StudentService studentService;
@RequestMapping(value = "/home")
public String page(){
return "home";
}
@ResponseBody
@RequestMapping(value ="/getall")
public List<Student> getAll(){
return studentService.selectAll();
}
}
- StudentMapper接口
package com.lanou.mapper;
import com.lanou.bean.Student;
import java.util.List;
/**
* Created by dllo
*/
public interface StudentMapper {
List<Student> selectAll();
}
- StudentMapper.xml
<?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="com.lanou.mapper.StudentMapper">
<cache type="com.lanou.cache.RedisCache"/>
<resultMap id="StudentMap" type="com.lanou.bean.Student">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="hobby" property="hobby"/>
</resultMap>
<select id="selectAll" resultMap="StudentMap">
SELECT * FROM student
</select>
</mapper>
- StudentService接口
package com.lanou.service;
import com.lanou.bean.Student;
import java.util.List;
/**
* Created by dllo
*/
public interface StudentService {
List<Student> selectAll();
}
- StudentServiceImpl类
package com.lanou.service.impl;
import com.lanou.bean.Student;
import com.lanou.mapper.StudentMapper;
import com.lanou.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* Created by dllo
*/
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentMapper studentMapper;
@Override
public List<Student> selectAll() {
return studentMapper.selectAll();
}
}
- mybatis-config.xml
<?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">
<configuration>
<settings>
<!-- Globally enables or disables any caches configured in any mapper under this configuration -->
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
<!-- Sets the number of seconds the driver will wait for a response from the database -->
<setting name="defaultStatementTimeout" value="3000"/>
<!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- Allows JDBC support for generated keys. A compatible driver is required.
This setting forces generated keys to be used if set to true,
as some drivers deny compatibility but still work -->
<setting name="useGeneratedKeys" value="true"/>
</settings>
<!-- Continue going here -->
</configuration>
- sum-mybatis.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.xsd">
<bean class="org.apache.commons.dbcp2.BasicDataSource" id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db1106"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sqlSessionFactory">
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/lanou/mapper/*.xml"/>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lanou.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
ssm-redis.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"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="redis.clients.jedis.JedisPoolConfig" id="poolConfig">
<property name="maxIdle" value="300"/>
<property name="maxTotal" value="600"/>
<property name="maxWaitMillis" value="1000"/>
<property name="testOnBorrow" value="true"/>
</bean>
<bean class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
id="jedisConnectionFactory"
p:host-name="127.0.0.1"
p:password="123456"
p:port="6379"
p:poolConfig-ref="poolConfig">
</bean>
<bean class="com.lanou.cache.RedisCacheTransfer" id="cacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
</bean>
</beans>
sam-servlet.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"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.lanou"/>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
<property name="prefix" value="/WEB-INF/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ssm-mybatis.xml,classpath:ssm-redis.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>SSMServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ssm-servlet.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>SSMServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.lanou</groupId>
<artifactId>1106-SSM-Lucene</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>1106-SSM-Lucene Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<!--分页插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.6.3</version>
</dependency>
<!--shiro-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.7.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-all</artifactId>
<version>1.2.3</version>
</dependency>
<!--Lucene需要的依赖-->
<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-core -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>6.1.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-queryparser -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queryparser</artifactId>
<version>6.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-analyzers-common -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-analyzers-common</artifactId>
<version>6.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-queries -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-queries</artifactId>
<version>6.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.lucene/lucene-highlighter -->
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-highlighter</artifactId>
<version>6.0.0</version>
</dependency>
<!--FileUtils,文件读取依赖-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!--分词器的插件-->
<dependency>
<groupId>com.hankcs.nlp</groupId>
<artifactId>hanlp-lucene-plugin</artifactId>
<version>1.1.2</version>
</dependency>
<!--Redis的依赖-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.7.2.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>1106-SSM-Lucene</finalName>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.tld</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>