说明:下面的这些配置类SpringDataRedisConfig.java,DatabaseConfig .java文件需要在spring-base.xml配置文件中定义扫描这些配置类所在的包(扫描包),然后其他类中需要使用的时候直接采用@Autoried(自动注入)注解注入即可。
使用缓存:RedisCache .java,然后在spring-cache.xml配置文件中引入此类。
1.导入web项目,创建authentication模块,并修改pom.xml文件
2.将profiles文件粘贴到authentication模块中,profiles文件夹里面有两个文件database.properties和redis.properties文件
修改database.properties中的数据库连接属性(用户名,密码,数据库名称等),修改redis.properties文件redis属性(可能修改主机地址,连接密码)
3.创建server-common模块,配置相应pom文件,并且在父pom文件中定义此模块,然后在authentication模块中引用此模块,在server-common模块的src/main/com.yootk.server.config/粘贴SpringDataRedisConfig.java文件
package com.yootk.server.config;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@PropertySource("classpath:redis.properties")
public class SpringDataRedisConfig {
@Bean("redisConfiguration")
public RedisStandaloneConfiguration getRedisConfiguration(
@Value("${redis.host}") String hostName ,
@Value("${redis.port}") int port,
@Value("${redis.auth}") String password,
@Value("${redis.database}") int database
) {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration() ;
configuration.setHostName(hostName); // 设置Redis主机名称
configuration.setPort(port); // 设置Redis的访问端口
configuration.setPassword(RedisPassword.of(password)); // 设置密码
configuration.setDatabase(database); // 设置数据库索引
return configuration ;
}
@Bean("objectPoolConfig")
public GenericObjectPoolConfig getObjectPoolConfig(
@Value("${redis.pool.maxTotal}") int maxTotal ,
@Value("${redis.pool.maxIdle}") int maxIdle ,
@Value("${redis.pool.minIdle}") int minIdle ,
@Value("${redis.pool.testOnBorrow}") boolean testOnBorrow
) {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig() ;
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setTestOnBorrow(testOnBorrow);
return poolConfig ;
}
@Bean("lettuceClientConfiguration")
public LettuceClientConfiguration getLettuceClientConfiguration(
@Autowired GenericObjectPoolConfig poolConfig
) { // 创建Lettuce组件的连接池客户端配置对象
return LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build() ;
}
@Bean("redisConnectionFactory")
public RedisConnectionFactory getConnectionFactory(
@Autowired RedisStandaloneConfiguration redisConfiguration ,
@Autowired LettuceClientConfiguration lettuceClientConfiguration
) {
LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(redisConfiguration,lettuceClientConfiguration) ;
return connectionFactory ;
}
@Bean("redisTemplate")
public RedisTemplate getRedisTempalate(
@Autowired RedisConnectionFactory connectionFactory
) {
RedisTemplate<Object,Object> redisTemplate = new RedisTemplate<>() ;
redisTemplate.setConnectionFactory(connectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); // 保存的value为对象
redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // 数据的key通过字符串存储
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); // 保存的value为对象
return redisTemplate ;
}
}
4.在server-common模块的src/main/com.yootk.server.config/粘贴DatabaseConfig.class文件,写完之后spring-database.xml配置文件就没用了,删除掉它。
package com.yootk.server.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.repository.NoRepositoryBean;
import javax.sql.DataSource;
import java.sql.SQLException;
@Configuration
@PropertySource("classpath:database.properties")
public class DatabaseConfig {
@Value("${db.druid.driverClassName}")
private String driverClassName ;
@Value("${db.druid.url}")
private String url ;
@Value("${db.druid.username}")
private String username ;
@Value("${db.druid.password}")
private String password ;
@Value("${db.druid.maxActive}")
private int maxActive ;
@Value("${db.druid.minIdle}")
private int minIdle ;
@Value("${db.druid.initialSize}")
private int initialSize ;
@Value("${db.druid.maxWait}")
private long maxWait ;
@Value("${db.druid.timeBetweenEvictionRunsMillis}")
private long timeBetweenEvictionRunsMillis ;
@Value("${db.druid.minEvictableIdleTimeMillis}")
private long minEvictableIdleTimeMillis ;
@Value("${db.druid.validationQuery}")
private String validationQuery ;
@Value("${db.druid.testWhileIdle}")
private boolean testWhileIdle ;
@Value("${db.druid.testOnBorrow}")
private boolean testOnBorrow ;
@Value("${db.druid.testOnReturn}")
private boolean testOnReturn ;
@Value("${db.druid.poolPreparedStatements}")
private boolean poolPreparedStatements ;
@Value("${db.druid.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize ;
@Value("${db.druid.filters}")
private String filters ;
@Bean("dataSource")
public DataSource getDruidDataSource() {
DruidDataSource dataSource = new DruidDataSource() ;
dataSource.setDriverClassName(this.driverClassName);
dataSource.setUrl(this.url);
dataSource.setUsername(this.username);
dataSource.setPassword(this.password);
dataSource.setMaxActive(this.maxActive);
dataSource.setMinIdle(this.minIdle);
dataSource.setInitialSize(this.initialSize);
dataSource.setMaxWait(this.maxWait);
dataSource.setTimeBetweenEvictionRunsMillis(this.timeBetweenEvictionRunsMillis);
dataSource.setMinEvictableIdleTimeMillis(this.minEvictableIdleTimeMillis);
dataSource.setValidationQuery(this.validationQuery);
dataSource.setTestWhileIdle(this.testWhileIdle);
dataSource.setTestOnBorrow(this.testOnBorrow);
dataSource.setTestOnReturn(this.testOnReturn);
dataSource.setPoolPreparedStatements(this.poolPreparedStatements);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(this.maxPoolPreparedStatementPerConnectionSize);
try {
dataSource.setFilters(this.filters);
} catch (SQLException e) {
e.printStackTrace();
}
return dataSource ;
}
}
5.在server-common模块的src/main/com.yootk.server.cache目录下粘贴RedisCache.java文件
package com.yootk.server.cache;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import org.springframework.data.redis.core.RedisTemplate;
import java.util.concurrent.Callable;
public class RedisCache implements Cache {
private RedisTemplate<String,Object> redisTemplate ;
private String name ; // 缓存名称
// 此时进行的Redis缓存操作实现类型需要通过配置文件的形式完成
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
@Override
public Object getNativeCache() {
return this.redisTemplate;
}
@Override
public ValueWrapper get(Object o) {
Object result = this.redisTemplate.opsForValue().get(String.valueOf(o)) ;
if (result != null) { // 已经查找到相应数据
return new SimpleValueWrapper(result) ;
}
return null;
}
@Override
public <T> T get(Object o, Class<T> aClass) {
Object result = this.redisTemplate.opsForValue().get(String.valueOf(o)) ;
if (result != null) { // 已经查找到相应数据
return (T) result ;
}
return null;
}
@Override
public <T> T get(Object o, Callable<T> callable) {
return null;
}
@Override
public void put(Object key, Object value) {
this.redisTemplate.opsForValue().set(String.valueOf(key),value);
}
@Override
public ValueWrapper putIfAbsent(Object key, Object value) {
Object result = this.redisTemplate.opsForValue().get(String.valueOf(key)) ;
if (result == null) {
this.redisTemplate.opsForValue().set(String.valueOf(key),value);
return new SimpleValueWrapper(value) ;
}
return new SimpleValueWrapper(result);
}
@Override
public void evict(Object o) {
this.redisTemplate.delete(String.valueOf(o)) ;
}
@Override
public void clear() {
this.redisTemplate.getConnectionFactory().getConnection().flushDb();
}
}
6.