RoleMapper接口:
package com.wbg.springRedis.dao; import com.wbg.springRedis.entity.Role; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface RoleMapper { List<Role> listAll(); int add(Role role); }
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.wbg.springRedis.dao.RoleMapper"> <insert id="add" parameterType="com.wbg.springRedis.entity.Role"> insert into role(role_name,note) values(#{roleName},#{note}) </insert> <select id="listAll" resultType="com.wbg.springRedis.entity.Role"> select * from role </select> </mapper>
Role类:
package com.wbg.springRedis.entity; import java.io.Serializable; public class Role { private int id; private String roleName; private String note; @Override public String toString() { return "Role{" + "id=" + id + ", roleName=‘" + roleName + ‘\‘‘ + ", note=‘" + note + ‘\‘‘ + ‘}‘; } public Role() { } public Role(String roleName, String note) { this.roleName = roleName; this.note = note; } public Role(int id, String roleName, String note) { this.id = id; this.roleName = roleName; this.note = note; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
xml文件:
//纯java @Bean public JedisConnectionFactory jedisConnectionFactory(){ JedisConnectionFactory jcf = new JedisConnectionFactory(); jcf.setHostName("localhost"); return jcf; } @Bean public RedisTemplate redisTemplate(){ RedisTemplate rt = new RedisTemplate(); rt.setConnectionFactory(jedisConnectionFactory()); rt.setKeySerializer(new StringRedisSerializer()); rt.setValueSerializer(new StringRedisSerializer()); return rt; }
@Autowired private RedisTemplate redisTemplate; @Autowired private RoleMapper roleMapper;
public List<Role> listRole() throws IOException { //使用jackJson序列化 ObjectMapper om = new ObjectMapper(); //键 String key = "listRole"; //原生 //Jedis jedis = new Jedis(); /* if (jedis.exists(key)){ return om.readValue(jedis.get(key), new TypeReference<List<Role>>(){}); }*/ //如果存在 就返回 if (redisTemplate.hasKey(key)){ return om.readValue((String) redisTemplate.opsForValue().get(key), new TypeReference<List<Role>>() { }); } List<Role> list = roleMapper.listAll(); //原生设置值 //jedis.set(key, om.writeValueAsString(list)); //设置 redisTemplate.opsForValue().set(key, om.writeValueAsString(list)); return list; }
原文地址:https://www.cnblogs.com/weibanggang/p/10184240.html
时间: 2024-10-25 21:01:26