jedis使用_redis从在linux下安装到项目使用

1,首先先从网上下载redis安装包

http://download.redis.io/releases/redis-4.0.10.tar.gz

2,然后使用FileZilla将压缩包上传至linux中

v2-8e8ef077828b8120ce110b39733d47a3_b.jpg

3,再用putty连接linux ,设置window为Change the size of the fort (可以复制粘贴)

设置Connection的时间(这样就算一段时间不使用putty也不会关闭)

v2-ecc8d97724e93bafc769eb788db0eee7_b.jpg

v2-5435ec5be0d8b6e1df01dc1800975edc_b.jpg

v2-279bf843cd021a83ccc9767449c004ff_b.jpg

4, cd到你安装redis的目录执行解压命令

tar -zxvf redis-4.0.11.tar.gz ,这时会多一个文件,cd进去进行编译,看到

Hint: It.....说明编译成功了

v2-f8b9e9c80f709d8dc293a2b3cf3f67d5_b.jpg

v2-075ad4840808b931dc5fa08b6207fafc_b.jpg

v2-647557e025cfec7f1c20b3ba8680db30_b.jpg

5,接下来要进行安装 PREFIX后面是你指定的安装目录(一般都在usr目录下)

make install PREFIX=/usr/local/redis ,看到下面的♂说明安装完成了,

v2-406c3c294ea5fe20fb61141839734c7b_b.jpg

6,把把/root/redis-4.0.11/redis.conf复制到/usr/local/redis/bin目录下

cp redis.conf /usr/local/redis/bin/

再cd到/usr/local/redis/bin下会看到这样的目录结构

v2-fd5a8675597dcc49379b51e1995cc248_b.jpg

7,接下来就对redis进行配置,vim redis.conf ,将bind注释到,requirepass是设置密码的

daemonize是是否允许远程登陆的

v2-b9eef8ea7cca5d73155249a8406743b3_b.png

v2-0ef4716f0d70a60f78b6e45b8e2e1d6f_b.jpg

v2-fdb70d0e1727de7621fa8e98df509df2_b.jpg

8,开启redis ./redis-server redis.conf, 再输入ps aux|grep redis查看redis的进程到到下图说明成功开启了。

v2-0c65fd5c9ca2f2ba8f7362a78071bb70_b.png

9,关闭操作有两种一种kill -9 还有一种如下图 如何没有设置密码直接./redis-cli

然后shutdown,设置密码的话需要在输入auth 你的密码。(输入quit退出)

v2-c74ca78e2e1a8d23b304cc467e95f6cb_b.jpg

到这里redis的安装与配置就已经全部完成了,接下来,就是项目运用了。

项目我分为2个项目,一个是ssm项目,另一个是springboot项目。

1,准备工作,

(1)安装redis客户端RedisDesktopManager(这个在网上有很多,这里就不多说了,有不会的可以私信我)

(2)连接redis

v2-08f68519cd6eea2e993eb78f15a2e5b8_b.jpg

2,编辑applicationContext-redis.xml文件

<?

3,添加依赖jedis是redis的组件,jackson是用来处理数据的。

                 <dependency>
			<groupId>redis.clients</groupId>
			<artifactId>jedis</artifactId>
			<version>2.9.0</version>
		</dependency>
                 <dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.8.3</version>
		</dependency>

4,引一个jsonUtil工具类,和一个jedisClient的接口,以及其实现类

package com.sesame.utils;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 
 */
public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
    	try {
			String string = MAPPER.writeValueAsString(data);
			return string;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 将json结果集转化为对象
     * 
     * @param jsonData json数据
     * @param clazz 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            T t = MAPPER.readValue(jsonData, beanType);
            return t;
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return null;
    }
    
    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
    	JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
    	try {
    		List<T> list = MAPPER.readValue(jsonData, javaType);
    		return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    	return null;
    }
    
}



package com.sesame.redis;


public interface JedisClient {

	String set(String key, String value);
	String get(String key);
	Boolean exists(String key);
	Long expire(String key, int seconds);
	Long ttl(String key);
	Long incr(String key);
	Long hset(String key, String field, String value);
	String hget(String key, String field);	
	Long hdel(String key,String... field);//删除hkey
	
}


package com.sesame.redis;

import org.springframework.beans.factory.annotation.Autowired;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class JedisClientPool implements JedisClient {
	
	@Autowired
	private JedisPool jedisPool;

	@Override
	public String set(String key, String value) {
		Jedis jedis = jedisPool.getResource();
		String result = jedis.set(key, value);
		jedis.close();
		return result;
	}

	@Override
	public String get(String key) {
		Jedis jedis = jedisPool.getResource();
		String result = jedis.get(key);
		jedis.close();
		return result;
	}
	@Override
	public Boolean exists(String key) {
		Jedis jedis = jedisPool.getResource();
		Boolean result = jedis.exists(key);
		jedis.close();
		return result;
	}

	@Override
	public Long expire(String key, int seconds) {
		Jedis jedis = jedisPool.getResource();
		Long result = jedis.expire(key, seconds);
		jedis.close();
		return result;
	}

	@Override
	public Long ttl(String key) {
		Jedis jedis = jedisPool.getResource();
		Long result = jedis.ttl(key);
		jedis.close();
		return result;
	}

	@Override
	public Long incr(String key) {
		Jedis jedis = jedisPool.getResource();
		Long result = jedis.incr(key);
		jedis.close();
		return result;
	}

	@Override
	public Long hset(String key, String field, String value) {
		Jedis jedis = jedisPool.getResource();
		
		Long result = jedis.hset(key, field, value);
		jedis.close();
		
		return result;
	}

	@Override
	public String hget(String key, String field) {
		Jedis jedis = jedisPool.getResource();
		String result = jedis.hget(key, field);
		jedis.close();
		return result;
	}

	@Override
	public Long hdel(String key, String... field) {
		Jedis jedis = jedisPool.getResource();
		Long hdel = jedis.hdel(key, field);
		jedis.close();
		return hdel;
	}	

}

5,接下来就可以编写代码了,定义一个Student的表

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '    主键    ',
  `name` varchar(50) DEFAULT NULL COMMENT '    名字    ',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='学生表'

6,同样需要在项目中定义一个Student的POJO

package com.sesame.wx.liyuan.bean;

import java.io.Serializable;

public class Student implements Serializable{
	
	private static final long serialVersionUID = 1L;

	private Integer id;
	
	private String name;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	

}

7,Dao层

public Student getStudent(Integer stuId);

<select id="getStudent" resultType="com.sesame.wx.liyuan.bean.Student" parameterType="Integer">
      select id, name from student where id = #{stuId}
</select>

8,Service层

public Student getStudent(Integer stuId) {
		try {
			String jsonstr = client.get("CONTENT_KEY"+stuId);//从redis数据库中获取内容分类下的所有的内容。
			//如果存在,说明有缓存
			if(StringUtil.isNotEmpty(jsonstr)){
			System.out.println("这里有缓存啦!!!!!");
				return JsonUtils.jsonToPojo(jsonstr, Student.class); //将json数据转为POJO对象
			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		Student student = liyuanDao.getStudent(stuId);
		try {
			System.out.println("没有缓存!!!!!!");
			client.set("CONTENT_KEY"+stuId, JsonUtils.objectToJson(student)); // 将数据转为json数据传入redis数据库
			client.expire("CONTENT_KEY"+stuId, 100); // 设置缓存时间,单位为秒
		} catch (Exception e) {
			e.printStackTrace();
		}
		return student;
	}

9,Controller层

	@RequestMapping("/getStudent")
	@ResponseBody
	public Map getStudent(Integer stuId) {
		Map resMap = new HashMap();
		Student student = liyuanSercice.getStudent(stuId);
		resMap.put("student", student);
		return resMap;
	
	}

10,接下来就进行测试,启动项目在浏览器输入你的地址,本狗的是http://localhost:8080/cj_app_api/wx/liyuan/getStudent?stuId=87

当看到下面的图片,说明缓存成功了。TTL是你设置的缓存时间

v2-5e53def657dafd4843244c6768704db4_b.png

v2-1469312f84d3edef37eb820ca59097f6_b.png

v2-eb87ecdb20369e5a5fb3beb836e47663_b.jpg

上面就是ssm使用redis的全部过程了,接下来就介绍springboot项目使用redis,这里还使用了cache插件来整合redis看起来代码更简洁一点。

1,首先创建user表,(我们不在是学生了,变成用户了=-=)

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '    主键    ',
  `name` varchar(50) DEFAULT NULL COMMENT '    名字    ',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='用户表'

2,配置文件

yml
spring:
  redis:
    host: 192.168.92.128
    port: 6379
    password: 123456
  cache:
    type: redis
cache:
  expire-time: 180  // 设置过期时间

CONFIG
package com.walklake.log.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
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 org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

/**
 *  必须继承CachingConfigurerSupport,不然此类中生成的Bean不会生效(没有替换掉默认生成的,只是一个普通的bean)
 *  springboot默认生成的缓存管理器和redisTemplate支持的类型很有限,根本不满足我们的需求,会抛出如下异常:
 *      org.springframework.cache.interceptor.SimpleKey cannot be cast to java.lang.String
 */
@Configuration
@EnableCaching
public class SpringCacheRedisConfig extends CachingConfigurerSupport {

    @Value("${cache.expire-time:180}")
    private int expireTime;

    // 配置key生成器,作用于缓存管理器管理的所有缓存
    // 如果缓存注解(@Cacheable、@CacheEvict等)中指定key属性,那么会覆盖此key生成器
    @Bean
    public KeyGenerator keyGenerator() {
        return (target, method, params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

   // 缓存管理器管理的缓存都需要有对应的缓存空间,否则抛异常:No cache could be resolved for 'Builder...
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
        rcm.setDefaultExpiration(expireTime);               //设置缓存管理器管理的缓存的过期时间, 单位:秒
        return rcm;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

3,接下来就是项目了,先在pom文件添加依赖

	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
	<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

4,创建POJO

package com.walklake.log.entity;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table(name="user")
public class User implements Serializable {
	
	private static final long serialVersionUID = 1L;

	@Id
    @GeneratedValue(strategy = GenerationType.AUTO)
	private Integer id;
	
	private String name;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	

}

5,Dao层(这里springboot使用的是spring data,非常好用,有时间我写一个spring data的文章)

package com.walklake.log.dao;

import org.springframework.data.repository.CrudRepository;

import com.walklake.log.entity.User;


public interface UserDAO extends CrudRepository<User, Integer> {
	
	User findById(Integer id);

}

6,Service(cache插件 @Cacheable为查询,第一次走代码,第二次走redis,@CachePut为更新,每次都会走代码,并将返回值保存到redis数据库中,所以一定要有返回值,

不然会保存null,@CacheEvict为删除,@Caching为组合可以任意搭配前面的注解

package com.walklake.log.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import com.walklake.log.dao.UserDAO;
import com.walklake.log.entity.User;

@Service
public class UserService {
	
	public static final String CACHE_KEY = "myCache";
	
	@Autowired
	private UserDAO userDAO;
	
	public void saveUser(String name) {
		User user = new User();
		user.setName(name);
		userDAO.save(user);
	}

	
	@CacheEvict(value="user",key ="'myCache'+#id")
	public void deleteUser(Integer id) {
		userDAO.delete(id);
	}
	
	@CachePut(value = "user",key ="'myCache'+#user.getId()")
	public User updateUser(User user) {
		return userDAO.save(user);
	}
	

	@Cacheable(value="user",key ="'myCache'+#id")
	public User searchUser(Integer id) {
		return userDAO.findById(id);
	}
	
	@Caching(cacheable = {@Cacheable(value="user",key ="'myCache'+#id")},
		     put = {@CachePut(value = "user",key ="'myCache'+#user.getId()")},
		     evict = {@CacheEvict(value="user",key ="'myCache'+#id")}
		    )
	public User updateAndSelect(User user) {
		userDAO.delete(user.getId());
		return userDAO.save(user);
	}
}

7,Controller层

package com.walklake.log.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.walklake.log.entity.User;
import com.walklake.log.service.UserService;

/*
 * @Author:zjd
 * @Date:2019/5/13 15:29
 * @Detail:记录签到数据
 */
@RestController
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	@GetMapping("/save")
	@SuppressWarnings("rawtypes")
	public Map save(String name) {
		Map<String, String> resMap = new HashMap<String, String>();
		try {
			userService.saveUser(name);
			resMap.put("result", "保存成功");
		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", "保存失败");
		}
		return resMap;
	}

	@GetMapping("/delete")
	@SuppressWarnings("rawtypes")
	public Map delete(Integer id) {
		Map<String, String> resMap = new HashMap<String, String>();
		try {
			userService.deleteUser(id);
			resMap.put("result", "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", "删除失败");
		}
		return resMap;
	}
	
	@GetMapping("/update")
	@SuppressWarnings("rawtypes")
	public Map update(Integer id, String name) {
		Map<String, String> resMap = new HashMap<String, String>();
		User user = new User();
		user.setId(id);
		user.setName(name);
		try {
			userService.updateUser(user);
			resMap.put("result", "更新成功");
		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", "更新失败");
		}
		return resMap;
	}
	
	@GetMapping("/search")
	@SuppressWarnings("rawtypes")
	public Map search(Integer id) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			User user = userService.searchUser(id);
			resMap.put("result", user);
		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", "查询失败");
		}
		return resMap;
	}
	
	@GetMapping("/updateAndSelect")
	@SuppressWarnings("rawtypes")
	public Map updateAndSelect(Integer id, String name) {
		Map<String, String> resMap = new HashMap<String, String>();
		User user = new User();
		user.setId(id);
		user.setName(name);
		try {
			userService.updateUser(user);
			resMap.put("result", "更新成功");
		} catch (Exception e) {
			e.printStackTrace();
			resMap.put("result", "更新失败");
		}
		return resMap;
	}
}

8,接下来就进行测试了

(1)首先测试查询,看到下面的图片说明成功了

v2-5c0b25bff36cb3437e0f03506faaacff_b.jpg

v2-52b1cbae0f18adfb1d37922a3bd70f76_b.jpg

(2)然后测试更新,看到下面的图片说明成功了

v2-f0e66b7ea52eb952528f31021f524c69_b.png

v2-63750a98f7000ab9bd1587cec52f5749_b.jpg

(3)测试删除,看到下面的图片说明成功了

v2-a0915f7eb520bc0a70088670cc65974f_b.jpg

v2-f7b330f82d9d4194d1193e6ed5d529ef_b.jpg

(4)最后测试组合组件,看到下面的图片说明成功了

v2-a31fc71206164ead388a32a73a2c8835_b.jpg

v2-f6a3b3863f26af9c3d7d60ce7b716e08_b.jpg

全部搞定!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值