1、安装Redis

我们在VMware中安装CentOS 64位系统后,在用户目录下下载安装Redis。

下载redis目前最稳定版本也是功能最完善,集群支持最好并加入了sentinel(哨兵-高可用)功能的redis-stable版,
 
 
wget http://download.redis.io/releases/redis-stable.tar.gz
tar -xzvf redis-stable.tar.gz
cd redis-stable
make PREFIX=/usr/local/redis01 install
cd /usr/local/redis01/bin

加上`&`号使redis以后台程序方式运行

./redis-server &

或者也可以到 redis-stable/src目录下进行启动。

检测后台进程是否存在

ps -ef |grep redis

检测6379端口是否在监听

netstat -lntp | grep 6379

或者我们可以直接到redis-stable目录下修改配置文redis.conf,找到如下配置:

daemonize yes

# When running daemonized, Redis writes a pid file in /var/run/redis.pid by
# default. You can specify a custom pid file location here.
pidfile "/var/run/redis/redis01.pid"

# Accept connections on the specified port, default is 6379.
# If port 0 is specified Redis will not listen on a TCP socket.
port 7001

将daemonize值改为yes,修改进行pid的存在路径,然后重新指定一下port端口。

最后我们设置一下redis的log日志存放的地方,如果没有redis目录,需要切换到路径下进行新建。

logfile "/var/log/redis/redis01.log"

修改配置文件后我们需要指定使用哪个配置文件启动Redis

./redis-server ../redis.conf

用`redis-cli`客户端检测连接是否正常

./redis-cli
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> set key "hello world"
OK

我们可以在Windows下直接下载一个RedisClient直接连接VMware中安装的Redis即可。如下图。

如果连接不上,需要关闭一下防火墙,使用

iptables -F

来禁用linux的防火墙或者使用:

vi /etc/selinux/config

然后把修改 SELINUX=enforcing的值为disabled

 

Spring Boot集成Redis

在mazhi工程下新建Maven Module,名称为mazhi-redis,然后在 pom.xml文件中添加redis的包引用和spring boot的包引用,如下:

 <!-- Add typical dependencies for a web application -->
    <dependencies>
       <dependency>
			<groupId>org.mazhi</groupId>
			<artifactId>mazhi-core</artifactId>
			<version>0.0.1-SNAPSHOT</version>
	   </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
         <!-- redius  -->
	    <dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-data-redis</artifactId>
			<version>1.0.0.RELEASE</version>
		</dependency>
    </dependencies>

然后引入application.yml文件,指定端口为8081。并且在src/java/main的org.mazhi.redis目录下新建Application.java文件,内容如下:

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}

下面就来为系统配置Redis了,在org.mazhi.redis.config目录下新建RedisCacheConfig.java文件,内容如下:

@Configuration
@PropertySource(value = "classpath:/redis.properties")
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {

		  @Value("${spring.redis.host}")
		  private String host;
		  @Value("${spring.redis.port}")
		  private int port;
		  @Value("${spring.redis.timeout}")
		  private int timeout;

		  @Bean
		  public KeyGenerator wiselyKeyGenerator(){
		      return new KeyGenerator() {
		          public Object generate(Object target, Method method, Object... 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();
		          }
		      };
		  }
		  @Bean
		  public JedisConnectionFactory redisConnectionFactory() {
		      JedisConnectionFactory factory = new JedisConnectionFactory();
		      factory.setHostName(host);
		      factory.setPort(port);
		      factory.setTimeout(timeout); //设置连接超时时间
		      return factory;
		  }
		  @Bean
		  public CacheManager cacheManager(RedisTemplate redisTemplate) {
		      RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
		      // Number of seconds before expiration. Defaults to unlimited (0)
		      cacheManager.setDefaultExpiration(10); //设置key-value超时时间
		      return cacheManager;
		  }
		  @Bean
		  public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
		      StringRedisTemplate template = new StringRedisTemplate(factory);
		      setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
		      template.afterPropertiesSet();
		      return template;
		  }
		  private void setSerializer(StringRedisTemplate template) {
		      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);
		  }
}

然后新建redis.properties配置文件,内容如下:

spring.redis.database=0
spring.redis.host=192.168.2.129
# Login password of the redis server.
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-idle=8
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
spring.redis.port=7001
# Name of Redis server.
spring.redis.sentinel.master=
# Comma-separated list of host:port pairs.
spring.redis.sentinel.nodes=
spring.redis.timeout=0

注意指定spring.redis.host和spring.redis.port为你的redis配置。

在org.mazhi.redis.web目录下新建RedisTestCtrl.java,对Redis进行简单的CRUD操作,如下:

@RestController
@RequestMapping(value = "/redis")
public class RedisTestCtrl {
	@Autowired
	private StringRedisTemplate redisTemplate;

	@RequestMapping(value = "/addKey")
	public void addKey() {
		redisTemplate.execute(new RedisCallback<Object>() {
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(  // 插入键为test,值为hello的键值对
                        redisTemplate.getStringSerializer().serialize("test"),
                        redisTemplate.getStringSerializer().serialize("hello")
                );
                return null;
            }
       });  

	}

	@RequestMapping(value = "/deleteKey")
	public void deleteKey() {
		redisTemplate.delete("test");  // 删除数据库中键为test的键值对

	}
}

这样在浏览器中访问一下:

http://localhost:8081/redis/addKey

执行添加的url后,可以在RedisClient中查看,如下:

然后执行:

http://localhost:8081/redis/delete

查看RedisClient,键值被删除。

 
 
 
 
 
 
 
 
 
 
 
 
 
 

剑指架构师系列-Redis安装与使用的更多相关文章

  1. 剑指架构师系列-Redis集群部署

    初步搭建Redis集群 克隆已经安装Redis的虚拟机,我们使用这两个虚拟机中的Redis来搭建集群. master:192.168.2.129 端口:7001 slave:192.168.2.132 ...

  2. 剑指架构师系列-MySQL的安装及主从同步

    1.安装数据库 wget http://dev.mysql.com/get/mysql-community-release-el7-5.noarch.rpm rpm -ivh mysql-commun ...

  3. 剑指架构师系列-Nginx的安装与使用

    Nginx可以干许多事情,在这里我们主要使用Nginx的反向代理与负载均衡功能. 1.Nginx的下载安装 在安装Nginx前需要安装如下软件: GCC  Nginx是C写的,需要用GCC编译 PCR ...

  4. 剑指架构师系列-Logstash分布式系统的日志监控

    Logstash主要做由三部署组成: Collect:数据输入 Enrich:数据加工,如过滤,改写等 Transport:数据输出 下面来安装一下: wget https://download.el ...

  5. 剑指架构师系列-持续集成之Maven+Nexus+Jenkins+git+Spring boot

    1.Nexus与Maven 先说一下这个Maven是什么呢?大家都知道,Java社区发展的非常强大,封装各种功能的Jar包满天飞,那么如何才能方便的引入我们项目,为我所用呢?答案就是Maven,只需要 ...

  6. 剑指架构师系列-Linux下的调优

    1.I/O调优 CentOS下的iostat命令输出如下: $iostat -d -k 1 2 # 查看TPS和吞吐量 参数 -d 表示,显示设备(磁盘)使用状态:-k某些使用block为单位的列强制 ...

  7. 剑指架构师系列-MySQL调优

    介绍MySQL的调优手段,主要包括慢日志查询分析与Explain查询分析SQL执行计划 1.MySQL优化 1.慢日志查询分析 首先需要对慢日志进行一些设置,如下: SHOW VARIABLES LI ...

  8. 剑指架构师系列-ActiveMQ队列的使用

    安装ActiveMQ只需要下载包后解压,然后就可以启动与关闭ActiveMQ了,如下: ./activemq start ./activemq stop 访问管理页面: http://10.10.20 ...

  9. 剑指架构师系列-spring boot的logback日志记录

    Spring Boot集成了Logback日志系统. Logback的核心对象主要有3个:Logger.Appender.Layout 1.Logback Logger:日志的记录器 主要用于存放日志 ...

随机推荐

  1. vue.js+socket.io+express+mongodb打造在线聊天[二]

    vue.js+socket.io+express+mongodb打造在线聊天[二] 在线地址观看 http://www.chenleiming.com github地址 https://github. ...

  2. 用UIWebView加载本地图片和gif图

    加载gif图: NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@" ...

  3. python——模块与包2

    模块与包2 1 什么是包 包是一种通过使用.'模块名'来组织python模块名称空间的方式. 无论是import形式还是from...import形式,凡是在导入语句中(而不是在使用时)遇到带点的,都 ...

  4. uvalive 3213 Ancient Cipher

    https://vjudge.net/problem/UVALive-3213 题意: 输入两个字符串,问是否可以由第一个字符串的每个字符一一映射得到第二个字符串,字符是可以随意移动的. 思路: 统计 ...

  5. Redis常用命令总结

    在Redis中一共有五种数据类型. 一.String 类型操作 //添加 set key value //查询 get key //删除 del key //拼接 append key value(返 ...

  6. libevent源码阅读笔记(一):libevent对epoll的封装

    title: libevent源码阅读笔记(一):libevent对epoll的封装 最近开始阅读网络库libevent的源码,阅读源码之前,大致看了张亮写的几篇博文(libevent源码深度剖析 h ...

  7. 我花了 8 小时,"掌握"了一下 Flutter | Flutter 中文站上线

    Hi,大家好,我是承香墨影! 距离 Google 在 2018 世界移动大会上发布 Flutter 的 Beta 版本,Flutter 是 Google 用以帮助开发者在 Android 和 iOS ...

  8. [LeetCode] Beautiful Arrangement 优美排列

    Suppose you have N integers from 1 to N. We define a beautiful arrangement as an array that is const ...

  9. postgresql 定时任务备份及恢复

    编写 脚本文件 如bak.sh,内容如下: ls_date=`date "+%Y%m%d%H%M%S"` pg_dump -U postgres -Ft yourdbname &g ...

  10. 持久化 XSS:ServiceWorkers 利用

    来源:http://www.mottoin.com/95058.html 来源:https://www.owasp.org/images/3/35/2017-04-20-JSONPXSS.pdf Se ...