spring boot 整合 redis
使用spring 2.0 以上
注:该案例没有设置某一个key具体的设置有效的时间,如有知道的,请下方留言(感激不尽)
实体类的配置:
package com.example.redis.redis.entity;
import java.io.Serializable;
import java.util.List;
public class UserInfo implements Serializable {
private Integer uid;
private String username;//帐号
private String name;//名称(昵称或者真实姓名,不同系统不同定义)
private String password; //密码;
private String salt;//加密密码的盐
private byte state;//用户状态,0:创建未认证(比如没有激活,没有输入验证码等等)--等待验证的用户 , 1:正常状态,2:用户被锁定.
private List<SysRole> roleList;// 一个用户具有多个角色
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public byte getState() {
return state;
}
public void setState(byte state) {
this.state = state;
}
public List<SysRole> getRoleList() {
return roleList;
}
public void setRoleList(List<SysRole> roleList) {
this.roleList = roleList;
}
/**
* 密码盐.
*
* @return
*/
public String getCredentialsSalt() {
return this.username + this.salt;
}
//重新对盐重新进行了定义,用户名+salt,这样就更加不容易被破解
@Override
public String toString() {
return "UserInfo{" +
"uid=" + uid +
", username='" + username + '\'' +
", name='" + name + '\'' +
", password='" + password + '\'' +
", salt='" + salt + '\'' +
", state=" + state +
", roleList=" + roleList +
'}';
}
}
redisConfing的配置
package com.example.redis.redis.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.stream.Collectors;
@Configuration
@EnableCaching
@Cacheable()
public class redisConfig extends CachingConfigurerSupport {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
//
// /**
// * 用于生成主键的策略
// *
// * @return
// */
@Bean
public KeyGenerator wiselyKeyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append("." + method.getName());
if (params == null || params.length == 0 || params[0] == null) {
return null;
}
String join = String.join("&", Arrays.stream(params).map(Object::toString).collect(Collectors.toList()));
String format = String.format("%s{%s}", sb.toString(), join);
//log.info("缓存key:" + format);
return "a2";
}
};
}
}
controller
package com.example.redis.redis.controller;
import com.example.redis.redis.userServer.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import java.util.HashMap;
import java.util.Map;
@Component
public class controller {
@Autowired
private UserInfo userInfo;
public void add() {
com.example.redis.redis.entity.UserInfo admin = userInfo.findByUsername("admin");
}
public void update(){
Map<Object, Object> map = new HashMap<>();
map.put("admin","admin");
map.put("name","管理员1");
userInfo.updateByusername(map);
}
}
Mapper
package com.example.redis.redis.Dao;
import com.example.redis.redis.entity.UserInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
import java.util.Map;
@org.apache.ibatis.annotations.Mapper
@Component
// 表示该类中可能有多个缓存,有些缓存可能是一致的
public interface Mapper {
UserInfo findByUsername(@Param("username") String username);
void updateByusername( Map map );
}
serverimpl
package com.example.redis.redis.userServer.impl;
import com.example.redis.redis.Dao.Mapper;
import com.example.redis.redis.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.Map;
@Service
//@CacheConfig(cacheNames = "users")
public class UserInfoImpl implements com.example.redis.redis.userServer.UserInfo {
@Autowired
private Mapper mapper;
@Override
@Cacheable(value = "all2", keyGenerator = "wiselyKeyGenerator")
public UserInfo findByUsername(String name) {
UserInfo mapperByUsername = mapper.findByUsername(name);
System.out.println("数据库读取数据....");
return mapperByUsername;
}
@Override
@CacheEvict(value = "all2",allEntries = true) // 在使用删除的时候,需要全部清除,如果一条一条的清除,效率会很低
public void updateByusername(Map map) {
mapper.updateByusername(map);
}
}
service接口
package com.example.redis.redis.userServer;
import java.util.Map;
public interface UserInfo {
com.example.redis.redis.entity.UserInfo findByUsername(String admin);
void updateByusername(Map map );
}
Application
package com.example.redis.redis;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@SpringBootApplication
@EnableCaching // 启动缓存
public class RedisApplication {
public static void main(String[] args) {
SpringApplication.run(RedisApplication.class, args);
}
/**
* 重新配置RedisCacheManager
*
* @param rd
*/
}
Mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.redis.redis.Dao.Mapper">
<resultMap id="map" type="com.example.redis.redis.entity.UserInfo">
<id property="uid" column="uid"></id>
<result property="username" column="username"></result>
<result property="name" column="name"></result>
<result property="password" column="password"></result>
<result property="salt" column="salt"></result>
<result property="state" column="state"></result>
<!--id,description,role,available-->
<collection property="roleList" ofType="com.example.redis.redis.entity.SysRole">
<id property="id" column="id"></id>
<result property="role" column="role"></result>
<result property="description" column="description"></result>
<result property="available" column="available"></result>
<!--id,name,resourceType,url,permission,parentId,parentIds,available-->
<collection property="permissions" ofType="com.example.redis.redis.entity.SysPermission">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="resourceType" column="resourceType"></result>
<result property="url" column="url"></result>
<result property="permission" column="permission"></result>
<result property="parentId" column="parentId"></result>
<result property="parentIds" column="parentIds"></result>
<result property="available" column="available"></result>
</collection>
</collection>
</resultMap>
<select id="findByUsername" parameterType="java.lang.String" resultMap="map">
SELECT *
FROM user_info
INNER JOIN sys_user_role ON user_info.uid = sys_user_role.uid
INNER JOIN sys_role ON role_id = sys_role.id
INNER JOIN sys_role_permission ON sys_role.id = sys_role_permission.role_id
INNER JOIN sys_permission ON permissionid = sys_role_permission.id
<where>
<if test="username != null and username !=''">
username = #{username} group by username
</if>
</where>
</select>
<!--<select id="findByUsername" parameterType="java.lang.String" resultType="com.sgqing.demo.entity.UserInfo">-->
<!--SELECT *-->
<!--FROM user_info-->
<!--WHERE username = #{username}-->
<!--</select>-->
<update id="updateByusername" parameterType="java.util.Map">
UPDATE user_info ui
SET ui.name = #{name}
WHERE ui.username = #{admin}
</update>
</mapper>
application.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&serverTimezone=UTC
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
redis:
database: 0
host: 127.0.0.1
port: 6379
password:
jedis:
pool:
max-active: 8
max-wait: -1
min-idle: 0
max-idle: 8
timeout: 1000
jpa:
show-sql: true
server:
port: 8081
mybatis:
typeAliasesPackage: com.example.redis.redis.Dao
mapperLocations: classpath:mapper/*.xml
Test 测试
package com.example.redis.redis.controller;
import com.example.redis.redis.userServer.UserInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class controllerTest {
@Autowired
private UserInfo userInfo;
// @Autowired
// StringRedisTemplate stringRedisTemplate;
// @Resource(name = "stringRedisTemplate")
// ValueOperations<String, String> valOpsStr;
// @Autowired
// RedisTemplate<Object, Object> redisTemplate;
//
// @Resource(name = "redisTemplate")
// ValueOperations<Object, Object> valOps;
@Test
public void test() {
com.example.redis.redis.entity.UserInfo admin = userInfo.findByUsername("admin");
System.out.println(admin);
}
@Test
public void test2() {
Map<String, String> map = new HashMap<>();
map.put("name", "管理员5");
map.put("admin", "admin");
userInfo.updateByusername(map);
}
}
如果不设置key的生成策略,可以只在application中开启缓存即可使用缓存的注解
效果
参考网址
https://blog.csdn.net/hry2015/article/details/75451705
用于设置不同的数据不同的缓存时间
@Cacheable(value = "people#${select.cache.timeout:1800}#${select.cache.refresh:600}", key = "#person.id", sync = true)
value属性上用#号隔开,第一个是原始的缓存容器名称,第二个是缓存的有效时间,第三个是缓存的自动刷新时间,单位都是秒
时间的设置如果存储在数据库中,可以首先将数据读取出来,用@ModelAttribute 注解,该注解会在当前类的所有的方法被调用之前执行,所以在请求方法很多的时候,该方法需要慎用,如果想要在所有的类,不只局限于当前类的所有的请求方法之前添加
@ModelAttribute 注解的方法,则需要在当前类上面添加@ControllerAdvice 参考网址https://www.cnblogs.com/magicalSam/p/7198420.html
2019-1-31
了解到,如果要单独设置每个属性的单独的时间,可以参考该网址
https://segmentfault.com/q/1010000015203664/a-1020000015209787
还没有评论,来说两句吧...